79

Instead of going JSON a json string and using $.parseJSON, I need to take my object and store it in a variable as string representing JSON.

(A library I'm dealing with expects a malformed JSON type so I need to mess around with it to get it to work.)

What's the best way to do this?

3
  • 1
    possible duplicate of Serializing to JSON in jQuery
    – Wolph
    Commented Aug 29, 2010 at 0:30
  • Which library expects a malformed JSON string? :/ Commented Aug 29, 2010 at 2:00
  • Stanford JavaScript Cryptography Library outputs and parses malformed JSON, the bug is bring worked on at the moment.
    – Incognito
    Commented Aug 29, 2010 at 5:15

5 Answers 5

84

Edit: You should use the json2.js library from Douglas Crockford instead of implementing the code below. It provides some extra features and better/older browser support.

Grab the json2.js file from: https://github.com/douglascrockford/JSON-js


// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

var tmp = {one: 1, two: "2"};
JSON.stringify(tmp); // '{"one":1,"two":"2"}'

Code from: http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/

4
  • 23
    I would recommend the json2.js library instead of this function, because it doesn't handle correctly some types, like properties containing undefined, functions, (which are not a valid JSON values), Boolean objects (e.g. new Boolean(true);), or NaN which should be replaced with null, etc... also it doesn't support the additional optional arguments, the replacer function and the spaces number for indentation, which are fully described in the standard. Commented Aug 29, 2010 at 1:29
  • 3
    i think perhaps the json2 link should be: github.com/douglascrockford/JSON-js/blob/master/json2.js Commented Oct 28, 2011 at 22:43
  • 5
    Most browsers have a native JSON object these days, which includes parse and stringify methods. So just try JSON.stringify({}) and see if you get "{}" without needing to include the above code. You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2) puts a newline and 2 spaces in front of each key. Commented Apr 3, 2012 at 15:49
  • For the ones looking for a modern answer: JSON.stringify(); is implemented in all the browsers (desktop and mobile): developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented Dec 20, 2016 at 13:24
39

I use

$.param(jsonObj)

which gets me the string.

2
  • 8
    But this does not create JSON (and that was the question). Commented Feb 23, 2011 at 17:11
  • 23
    but this little code is doing all the title of the question requests :P Commented Aug 18, 2011 at 9:08
35

Most browsers have a native JSON object these days, which includes parse and stringify methods. So just try JSON.stringify({}) and see if you get "{}". You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2) puts a newline and 2 spaces in front of each key.

JSON.stringify({a:1,b:2}, null, 2)

gives

"{\n  \"a\": 1,\n  \"b\": 2\n}"

which prints as

{
  "a": 1,
  "b": 2
}

As for the messing around part of your question, use the second parameter. From http://www.javascriptkit.com/jsref/json.shtml :

The replacer parameter can either be a function or an array of String/Numbers. It steps through each member within the JSON object to let you decide what value each member should be changed to. As a function it can return:

  • A number, string, or Boolean, which replaces the property's original value with the returned one.
  • An object, which is serialized then returned. Object methods or functions are not allowed, and are removed instead.
  • Null, which causes the property to be removed.

As an array, the values defined inside it corresponds to the names of the properties inside the JSON object that should be retained when converted into a JSON object.

10

The best way I have found is to use jQuery JSON

3
  • 1
    because it is a jquery plugin & not what's directly provided by jquery Commented Sep 22, 2012 at 7:47
  • @user01 but jquery doesn't include a way to do this (at least it didn't when I wrote this reply, not sure if it does now) Commented Apr 17, 2013 at 11:17
  • @DavidReynolds: yes of course, I understand:) I didn't intend any offence to you but just commented on this as a solution to problem :) Commented Apr 17, 2013 at 16:43
0

You could parse the JSON to an object, then create your malformed JSON from the ajavscript object. This may not be the best performance-wise, tho.

Otherwise, if you only need to make very small changes to the string, just treat it as a string, and mangle it using standard javascript.

Not the answer you're looking for? Browse other questions tagged or ask your own question.