How can I serialize an object to JSON in JavaScript?
4 Answers
You’re looking for JSON.stringify.
Examples:
const object = {
hello: "world",
"some array": [ 42, 69, 420, 1337, null, true ]
},
primitive = false;
console.log(JSON.stringify(object)); // "{\"hello\":\"world\",\"some array\":[42,69,420,1337,null,true]}"
console.log(JSON.stringify(primitive)); // "false"
2 Comments
Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js, include it and do
var json_data = JSON.stringify(obj);
2 Comments
json2.js anymore, unless you are targetting very old browsers: modern browsers include a native implementation of the JSON object. The good thing about json2.js is that it will only kick in if no native object is found. See [stackoverflow.com/questions/891299/… for a detailed breakdown of browser support.Just to keep it backward compatible I load Crockfords JSON-library from cloudflare CDN if no native JSON support is given (for simplicity using jQuery):
function winHasJSON(){
json_data = JSON.stringify(obj);
// ... (do stuff with json_data)
}
if(Object.prototype.hasOwnProperty.call(window, "JSON") && typeof JSON.stringify === 'function'){
winHasJSON();
} else {
$.getScript('//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min.js', winHasJSON)
}
1 Comment
typeof JSON === "object" is not a safe check. if(typeof JSON === 'object' && typeof JSON.stringify === 'function') will fail if, for whatever reason, JSON === null. You’re looking for an existence check. The correct way is if(Object.prototype.hasOwnProperty.call(window, "JSON") && typeof JSON.stringify === "function") (in modern browsers, it would be Object.hasOwn(globalThis, "JSON"), but, of course, modern browsers have JSON). According to Edurne Pascual’s comment, this check is actually redundant.How to work with JSON in Javascript
Having to work with JSON is a common situation in web development, this is why Javascript provides the JSON object with its static methods.
Parsing from string to object
To parse a JSON string into a Javascript object we can use JSON.parse()
let obj = JSON.parse('{"x": 325, "y": 896, "speed": 16.5}')
Result:
obj = {
x: 325,
y: 896,
speed: 16.5
}
Parsing from object to string
Converting a Javascript object to a string it's as easy as the inverse operation
let str = JSON.stringify({x: 325, y: 896, speed: 16.5})
Result:
str = '{"x": 325, "y": 896, "speed": 16.5}'