74

どうやらjQueryには、特定のオブジェクトまたは文字列をJSONオブジェクトにデコードする機能があります。ただし、サーバーに POST する必要がある JS オブジェクトがあり、JSON.stringify() 関数をラップするユーティリティが jQuery にありません。この機能は、Chrome、Safari 4、FF3.6、IE8 にはありますが、それ以前のブラウザーにはありません。それをサポートするブラウザーでネイティブに使用できますが、それ以外の場合は、Crockford の JSON スクリプトの使用にフォールバックする必要があります。

Crockford スクリプトの代わりに JSON のエンコードとデコードを処理する jQuery の組み込み機能はありますか?

4

6 に答える 6

29

これをチェックしてみてください: http://www.json.org/js.html

于 2010-02-17T00:15:56.810 に答える
27

"Closure Library" (Google) を使用して、クロス ブラウザーの JSON エンコーダー/デコーダーを作成できます。

http://closure-compiler.appspot.com/にアクセスしてください。

テキストフィールドに以下を挿入し、「コンパイル」をクリックします。

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @use_closure_library true
// ==/ClosureCompiler==

goog.require('goog.json');
if (!window['JSON']) window['JSON']={};
if (typeof window['JSON']['stringify'] !== 'function') window['JSON']['stringify']=goog.json.serialize;
if (typeof window['JSON']['parse'] !== 'function') window['JSON']['parse']=goog.json.parse;
于 2010-10-17T20:57:02.623 に答える
14

jQuery は、JSON 文字列をネイティブにデコードできますjQuery.parseJSON()

ただし、エンコーディングについては、プラグインしか知りません:jquery-json

于 2010-02-17T00:19:58.757 に答える
3

jQuery はこの機能を内部的に必要としないため、そのための便利なメソッドを提供しません。

JSON.stringify() は、オブジェクトをそのオブジェクトの JSON 文字列表現にエンコードする標準かつ推奨される方法です。これは、多くのブラウザーのネイティブ JSON オブジェクトのメソッドであり、json2.js (https://github.com/douglascrockford/JSON-js) を使用してフォールバックを提供することをお勧めします。

于 2012-03-13T00:39:13.503 に答える
2

stewe の回答に基づいて構築するために、Advancedがオンになっているクロージャ コンパイラは、1 文字の変数の束でグローバル名前空間を汚染するスクリプトを提供します。したがって、次のように無名関数呼び出しでラップするだけです。

(function() {
  function g(a) {
    var b = typeof a;
    if ("object" == b)
      if (a) {
        if (a instanceof Array) return "array";
        if (a instanceof Object) return b;
        var c = Object.prototype.toString.call(a);
        if ("[object Window]" == c) return "object";
        if ("[object Array]" == c || "number" == typeof a.length && "undefined" != typeof a.splice && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("splice")) return "array";
        if ("[object Function]" == c || "undefined" != typeof a.call && "undefined" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable("call")) return "function"
      } else return "null";
    else if ("function" == b && "undefined" == typeof a.call) return "object";
    return b
  };

  function h(a) {
    a = "" + a;
    if (/^\s*$/.test(a) ? 0 : /^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g, "@").replace(/"[^"\\\n\r\u2028\u2029\x00-\x08\x10-\x1f\x80-\x9f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g, ""))) try {
      return eval("(" + a + ")")
    } catch (b) {}
    throw Error("Invalid JSON string: " + a);
  }

  function i(a, b) {
    var c = [];
    j(new k(b), a, c);
    return c.join("")
  }

  function k(a) {
    this.a = a
  }

  function j(a, b, c) {
    switch (typeof b) {
      case "string":
        l(b, c);
        break;
      case "number":
        c.push(isFinite(b) && !isNaN(b) ? b : "null");
        break;
      case "boolean":
        c.push(b);
        break;
      case "undefined":
        c.push("null");
        break;
      case "object":
        if (null == b) {
          c.push("null");
          break
        }
        if ("array" == g(b)) {
          var f = b.length;
          c.push("[");
          for (var d = "", e = 0; e < f; e++) c.push(d), d = b[e], j(a, a.a ? a.a.call(b, "" + e, d) : d, c), d = ",";
          c.push("]");
          break
        }
        c.push("{");
        f = "";
        for (e in b) Object.prototype.hasOwnProperty.call(b, e) && (d = b[e], "function" != typeof d && (c.push(f), l(e, c), c.push(":"),
          j(a, a.a ? a.a.call(b, e, d) : d, c), f = ","));
        c.push("}");
        break;
      case "function":
        break;
      default:
        throw Error("Unknown type: " + typeof b);
    }
  }
  var m = {
      '"': '\\"',
      "\\": "\\\\",
      "/": "\\/",
      "\u0008": "\\b",
      "\u000c": "\\f",
      "\n": "\\n",
      "\r": "\\r",
      "\t": "\\t",
      "\x0B": "\\u000b"
    },
    n = /\uffff/.test("\uffff") ? /[\\\"\x00-\x1f\x7f-\uffff]/g : /[\\\"\x00-\x1f\x7f-\xff]/g;

  function l(a, b) {
    b.push('"', a.replace(n, function(a) {
      if (a in m) return m[a];
      var b = a.charCodeAt(0),
        d = "\\u";
      16 > b ? d += "000" : 256 > b ? d += "00" : 4096 > b && (d += "0");
      return m[a] = d + b.toString(16)
    }), '"')
  };
  window.JSON || (window.JSON = {});
  "function" !== typeof window.JSON.stringify && (window.JSON.stringify = i);
  "function" !== typeof window.JSON.parse && (window.JSON.parse = h);
})();

これで、次のように呼び出すことができます。

var JSONString = JSON.stringify({name: 'value'});

于 2012-03-30T18:25:39.100 に答える
1

多くの場合、jQuery を使用する場合、JSON.stringify() 関数は必要ありません。たとえば、ajax を使用して JavaScript データをサーバーに送信する一般的なケースを考えてみましょう。jquery には、これを処理するための組み込み関数があります

$.post("test.php", { name: "John", time: "2pm" } );
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
    alert("JSON Data: " + json.users[3].name);
});

上記のすべての例で、送信された JavaScript データは jQuery によって自動的にシリアル化されます。

これらの場合のシリアル化は JSON.Stringify() と同じではなく、代わりにデータが html クエリ文字列にシリアル化されます (参照: http://en.wikipedia.org/wiki/Query_string#Structure )。

ただし、この形式のシリアライゼーションは、ほとんどの (すべてではない) アプリケーションで問題ありません。

于 2012-03-14T19:20:47.530 に答える