thelolcat
thelolcat

Reputation: 11545

Reverse of JSON.stringify?

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

How can I turn the string back to an object?

Upvotes: 476

Views: 445962

Answers (8)

Chase Florell
Chase Florell

Reputation: 47377

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

Upvotes: 690

msillano
msillano

Reputation: 58

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

Upvotes: 1

Michael Anderson
Michael Anderson

Reputation: 73480

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

Upvotes: 89

Exception
Exception

Reputation: 8379

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

Upvotes: 6

Shaik Md N Rasool
Shaik Md N Rasool

Reputation: 500

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

Upvotes: 8

mg_dev
mg_dev

Reputation: 1403

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

Upvotes: 3

Mina Gabriel
Mina Gabriel

Reputation: 25080

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?

Upvotes: 8

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

JSON.parse is the opposite of JSON.stringify.

Upvotes: 103

Related Questions