Reputation: 7337
How can I serialize an object to JSON in JavaScript?
Upvotes: 213
Views: 262338
Reputation: 3093
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)
}
Upvotes: 4
Reputation: 16502
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"
Upvotes: 298
Reputation: 462
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}'
Upvotes: 0
Reputation: 54031
Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js
, include it and do
var json_data = JSON.stringify(obj);
Upvotes: 51