484

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

How can I turn the string back to an object?

6
  • 7
    Note that {foo: 'bar'} isn't valid JSON (while it is a valid javascript expression). Commented Jun 23, 2012 at 18:02
  • 2
    simply try JSON.parse. if your browser have no support then try json2.js Commented Jun 23, 2012 at 18:03
  • 11
    guys we're dealing with a lolcat here. Commented Jun 23, 2012 at 18:06
  • 1
    Maybe I should have added another (read fourth) answer saying you should do JSON.parse... Commented Jun 23, 2012 at 18:06
  • 37
    @RobW, turns out that your google link points back to this question as the top hit. #ironic Commented Nov 6, 2012 at 15:40

8 Answers 8

699

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

Sign up to request clarification or add additional context in comments.

2 Comments

Pro tip: always put JSON.parse() into try-catch structures, as the method can crash your Node/Js
Beware: JSON.parse( JSON.stringify( {one:1} )) will bite.
103

JSON.parse is the opposite of JSON.stringify.

Comments

91

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

8 Comments

Per the JSON SPEC "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
One example of this is that { bar:"bar" } (from your prototype) is not considered valid json since foo is a variable rather than a string. Valid json needs the key to be a string.
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.
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.
This is an outstandingly comprehensive answer, and far more worthy of being the accepted answer. Thank you for your excellent work.
|
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?

Comments

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

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.