I'm stringyfing an object like {'foo': 'bar'}
How can I turn the string back to an object?
69 Answers
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); }2JSON.parse is the opposite of JSON.stringify.
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
ownPropertiesof 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 ); // falseYou'll lose identity:
var o = {}; var oo = jsonrepack(o); console.log( o === oo ); // falseFunctions 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)); // falseObjects that provide a
toJSONfunction 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 8Recommended is to use JSON.parse
There is an alternative you can do :
var myObject = eval('(' + myJSONtext + ')'); Why is using the JavaScript eval function a bad idea?
0The native JSON object includes two key methods.
1. JSON.parse() 2. JSON.stringify() The
JSON.parse()method parses a JSON string - i.e. reconstructing the original JavaScript objectvar jsObject = JSON.parse(jsonString);JSON.stringify() method accepts a JavaScript object and returns its JSON equivalent.
var jsonString = JSON.stringify(jsObject);
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);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); 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: 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
$("#save").click(function () { debugger var xx = []; var dd = { "firstname": "", "lastname": "", "address": "" }; var otable1 = $("#table1").dataTable().fnGetData(); for (var i = 0; i < otable1.length; i++) { dd.firstname = otable1[i][0]; dd.lastname = otable1[i][1]; dd.address = otable1[i][2]; xx.push(dd); var dd = { "firstname": "", "lastname": "", "address": "" }; } JSON.stringify(alert(xx)); $.ajax({ url: '../Home/save', type: 'POST', data: JSON.stringify({ u: xx }), contentType: 'application/json;', dataType: 'json', success: function (event) { alert(event); $("#table2").dataTable().fnDraw(); location.reload(); } }); });