JSON stringify missing from jQuery 1.4.1?

64,748

Solution 1

You might want to check this out: http://www.json.org/js.html

Solution 2

You can use "Closure Library" (Google) to make a cross browser JSON encoder/decoder.

Just go to http://closure-compiler.appspot.com/

and insert the following into the text field, then hit "Compile":

// ==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;

Solution 3

jQuery can decode JSON strings natively with jQuery.parseJSON().

For encoding though, i only know of a plugin : jquery-json

Solution 4

jQuery does not need this functionality internally and thus does not provide a convenience method to do so.

JSON.stringify() is the standard and recommended way of encoding an object to a JSON string representation of that object. It is a method of the native JSON object in many browsers, and it is recommended you use json2.js (https://github.com/douglascrockford/JSON-js) to provide a fallback.

Solution 5

To build on stewe's answer, closure compiler with Advanced turned on gives you a script that pollutes the global namespace with a bunch of one letter variables. So, I just wrap it in an anonymous function call like so:

(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);
})();

Now you can call:

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

Share:
64,748
Geuis
Author by

Geuis

Updated on July 10, 2022

Comments

  • Geuis
    Geuis almost 2 years

    Apparently jQuery has the ability to decode a given object or string into a JSON object. However, I have a JS object that I need to POST back to the server and I find no utility in jQuery that wraps the JSON.stringify() function. That function is found in Chrome, Safari 4, FF3.6, and IE8 but is not found in earlier browsers. I can use it natively in the browsers that support it, but otherwise am forced to fall back to using Crockford's JSON scripts.

    Is there some built-in with jQuery that handles JSON encoding and decoding that takes the place of the Crockford scripts?

  • Geuis
    Geuis over 14 years
    Yeah, its kind of sad that jQuery hasn't added a method to do this directly to the library. I ended up minifying json.js with Closure compiler and stuck it in the bottom of my js file where I'm working. It'll do the trick, but seems unnecessary.
  • Gabriele Petrioli
    Gabriele Petrioli over 13 years
    @zcrar70, he specifically asks for a JSON.stringify wrapper.. unless your comment is intended for the OP.
  • Tomas
    Tomas about 13 years
    I think serialize should be changed to stringify to reuse the browsers native function if available
  • stewe
    stewe about 13 years
    renamed JSON.serialize to JSON.stringify
  • crsuarezf
    crsuarezf almost 13 years
    i've been using code.google.com/p/jquery-json solution. Works fine for me.
  • Josh Maag
    Josh Maag over 4 years
    Link is no longer functional. This answer doesn't really give an answer since it is just a link.