457

I'm stringyfing an object like {'foo': 'bar'}

How can I turn the string back to an object?

sohnryang
  • 725
  • 2
  • 13
  • 27
thelolcat
  • 10,995
  • 21
  • 60
  • 102

8 Answers8

668

You need to JSON.parse() your valid JSON 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);
}
Chase Florell
  • 46,378
  • 57
  • 186
  • 376
99

JSON.parse is the opposite of JSON.stringify.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
87

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
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
  • 1
    Per the [`JSON SPEC`](http://json.org/) *"JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others."*. To me this says that JSON should only be used for language agnostic types/data. Therefore, your example (while very valid) only relates to JSON in it's association to JavaScript, and should be more-so defined as JSONP, and not true JSON... IMO – Chase Florell May 26 '13 at 20:48
  • One example of this is that `{ bar:"bar" }` (from your prototype) is [not considered valid json](http://jsonlint.com/) since `foo` is a variable rather than a string. Valid json needs the `key` to be a `string`. – Chase Florell May 26 '13 at 20:53
  • 4
    I read the OP as saying "I converted a javascript object to a JSON string, and now I want to convert it back - how do I do it?" All the other answers say just use `JSON.parse`. I'm just warning that theres a lot of cases that will not handle correctly. If you're using pure primitive data (no classes, prototypes) and only the datatypes supported by JSON (no dates, XML, HTML etc. ) then you're OK. – Michael Anderson May 27 '13 at 00:17
  • Also in Javascript `X = { foo:"bar" }` is the same as `X = { "foo":"bar" }` which is the same as `X = {}; X.foo = "bar"` which is the same as `X={}; X["foo"] = "bar"` The resulting object is identical in all 4 cases. That makes no difference to the validity of the generated JSON. – Michael Anderson May 27 '13 at 00:21
  • 2
    This is an outstandingly comprehensive answer, and far more worthy of being the accepted answer. Thank you for your excellent work. – scubbo May 02 '15 at 19:23
  • neither `jsonrepack(new Date(1,2,1990));` nor `jsonrepack(new Date(1990,2,1));` returns `'1990-02-01T16:00:00.000Z'` for me, but `'1906-08-10T22:00:00.000Z'` and `'1990-02-28T23:00:00.000Z'` :P – Martin Schneider Mar 22 '17 at 21:34
  • @MA-Maddin you're right that it should be `jsonrepack(new Date(1990,2,1));` and I've corrected that. The reason you see a difference in the output for that case is the timezone you're using is different to mine - and `new Date(1990,2,1)` is the date for 1 Feb 1990 in the UTC timezone. – Michael Anderson Mar 23 '17 at 01:29
  • Great answer - thorough and beautifully QED. It also alerted me to a specific bump in the road that I was sure to hit. Thanks for going the extra mile. – jwolf Apr 29 '18 at 09:25
8

Recommended is to use JSON.parse

There is an alternative you can do :

 var myObject = eval('(' + myJSONtext + ')');

Json in javascript

Why is using the JavaScript eval function a bad idea?

Community
  • 1
  • 1
Mina Gabriel
  • 23,150
  • 26
  • 96
  • 124
8

http://jsbin.com/tidob/1/edit?js,console,output

The native JSON object includes two key methods.

1. JSON.parse()
2. JSON.stringify() 
  1. The JSON.parse() method parses a JSON string - i.e. reconstructing the original JavaScript object

    var jsObject = JSON.parse(jsonString);

  2. JSON.stringify() method accepts a JavaScript object and returns its JSON equivalent.

    var jsonString = JSON.stringify(jsObject);

Shaik Md N Rasool
  • 484
  • 1
  • 5
  • 13
6

How about this

var parsed = new Function('return ' + stringifiedJSON )();

This is a safer alternative for eval.

var stringifiedJSON = '{"hello":"world"}';
var parsed = new Function('return ' + stringifiedJSON)();
alert(parsed.hello);
Chase Florell
  • 46,378
  • 57
  • 186
  • 376
Exception
  • 8,111
  • 22
  • 85
  • 136
3

Check this out.
http://jsfiddle.net/LD55x/

Code:

var myobj = {};
myobj.name="javascriptisawesome";
myobj.age=25;
myobj.mobile=123456789;
debugger;
var str = JSON.stringify(myobj);
alert(str);
var obj = JSON.parse(str);
alert(obj);
Manish Gupta
  • 1,405
  • 14
  • 32
1

how about this partial solution?

I wanna store (using a Config node) a global bigobj, with data + methods (as an alternative to importing an external library), used in many function nodes on my flow:

Strange but it works: The global variable 'bigobj':

{
some[]more[]{dx:"here"} , // array of objects with  array of objects. The 'Config' node requires JSON.
.....
 "get_dx": "function( d,p) {  return this.some[d].more[p].dx; }"  // test function
}

i.e. a JSON version of a function.... (all in one line :( )

USE: Inside a function node:

var bigO = global.get("bigobj");

function callJSONMethod(obj, fname, a, b, c, d){
    // see: https://stackoverflow.com/questions/49125059/how-to-pass-parameters-to-an-eval-based-function-injavascript
var wrap = s => "{ return " + obj[fname] + " };" //return the block having function expression
var func = new Function(wrap(obj[fname]));
return func.call( null ).call( obj, a, b, c, d); //invoke the function using arguments
}

msg.payload =callJSONMethod(bigO, "get_dx", 2, 2); 
return msg:

returns "here", unbelieve!

i.e I must add the function callJSONMethod() to any function block using bigobj..... maybe acceptable.

Best regards

msillano
  • 48
  • 5