Reverse of JSON.stringify?
I'm stringyfing an object like {'foo': 'bar'}
How can I turn the string back to an object?
Solution 1:
You need to JSON.parse()
the string.
var str = '{"hello":"world"}';
try {
var obj = JSON.parse(str); // this is how you parse a string into JSON
document.body.innerHTML += obj.hello;
} catch (ex) {
console.error(ex);
}
Solution 2:
JSON.parse
is the opposite of JSON.stringify
.
Solution 3:
JSON.stringify
and JSON.parse
are almost oposites, and "usually" this kind of thing will work:
var obj = ...;
var json = JSON.stringify(obj);
var obj2 = JSON.parse(json);
so that obj and obj2 are "the same".
However there are some limitations to be aware of. Often these issues dont matter as you're dealing with simple objects. But I'll illustrate some of them here, using this helper function:
function jsonrepack( obj ) { return JSON.parse(JSON.stringify(obj) ); }
-
You'll only get
ownProperties
of the object and lose prototypes:var MyClass = function() { this.foo="foo"; } MyClass.prototype = { bar:"bar" } var o = new MyClass(); var oo = jsonrepack(o); console.log(oo.bar); // undefined console.log( oo instanceof MyClass ); // false
-
You'll lose identity:
var o = {}; var oo = jsonrepack(o); console.log( o === oo ); // false
-
Functions dont survive:
jsonrepack( { f:function(){} } ); // Returns {}
-
Date objects end up as strings:
jsonrepack(new Date(1990,2,1)); // Returns '1990-02-01T16:00:00.000Z'
-
Undefined values dont survive:
var v = { x:undefined } console.log("x" in v); // true console.log("x" in jsonrepack(v)); // false
-
Objects that provide a
toJSON
function may not behave correctly.x = { f:"foo", toJSON:function(){ return "EGAD"; } } jsonrepack(x) // Returns 'EGAD'
I'm sure there are issues with other built-in-types too. (All this was tested using node.js so you may get slightly different behaviour depending on your environment too).
When it does matter it can sometimes be overcome using the additional parameters of JSON.parse
and JSON.stringify
. For example:
function MyClass (v) {
this.date = new Date(v.year,1,1);
this.name = "an object";
};
MyClass.prototype.dance = function() {console.log("I'm dancing"); }
var o = new MyClass({year:2010});
var s = JSON.stringify(o);
// Smart unpack function
var o2 = JSON.parse( s, function(k,v){
if(k==="") {
var rv = new MyClass(1990,0,0);
rv.date = v.date;
rv.name = v.name;
return rv
} else if(k==="date") {
return new Date( Date.parse(v) );
} else { return v; } } );
console.log(o); // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o.constructor); // [Function: MyClass]
o.dance(); // I'm dancing
console.log(o2); // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o2.constructor) // [Function: MyClass]
o2.dance(); // I'm dancing