views:

222

answers:

2

Instead of going from 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?

A: 

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.

cofiem
+3  A: 
// 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/

Inigoesdr
I would recommend the [json2.js](http://www.json.org/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](http://ecma262-5.com/ELS5_HTML.htm#Section_15.12.3) in the standard.
CMS