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);
}
Answer from Chase Florell on Stack OverflowVideos
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);
}
JSON.parse is the opposite of JSON.stringify.
From the fine manual:
toJSON behavior
If an object being stringified has a property named
toJSONwhose value is a function, then thetoJSONmethod customizes JSON stringification behavior: instead of the object being serialized, the value returned by thetoJSONmethod when called will be serialized.
This is why Backbone uses the toJSON method for serialization and given a model instance called m, you can say things like:
var string = JSON.stringify(m);
and get just the attributes out of m rather than a bunch of noise that your server won't care about.
That said, the main difference is that toJSON produces a value (a number, boolean, object, ...) that gets converted to a JSON string whereas JSON.stringify always produces a string.
The default Backbone toJSON is simply this (for models):
return _.clone(this.attributes);
so m.toJSON() gives you a shallow copy of the model's attributes. If there are arrays or objects as attribute values then you will end unexpected reference sharing. Note that Backbone.Model#clone also suffers from this problem.
If you want to safely clone a model's data then you could send it through JSON.stringify and then JSON.parse to get a deep copy:
var data = JSON.parse(JSON.stringify(model_instance));
var cloned_model = new M(data);
where model_instance is your instance of the Backbone model M.
JSON.stringify()- Any valid JSON representation value can be stringified.The
JSON.stringify(..)utility will automatically omitundefined,function, andsymbolvalues when it comes across them. If such a value is found in anarray, that value is replaced bynull(so that the array position information isn't altered). If found as a property of anobject, that property will simply be excluded.JSON stringification has the special behavior that if an
objectvalue has atoJSON()method defined, this method will be called first to get a value to use for serialization.toJSON()- to a valid JSON value suitable for stringification.One example,
JSON.stringify()anobjectwith circular reference in it, an error will be thrown.toJSON()can fix it as following.var o = { }; var a = { b: 32, c: o }; // circular reference o.d = a; // JSON.stringify( a ); // an error caused by circular reference // define toJSON method a.toJSON = function() { return { b: this.b }; }; JSON.stringify( a ); // "{"b":32}"