214

How can I serialize an object to JSON in JavaScript?

4 Answers 4

298

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"

Sign up to request clarification or add additional context in comments.

2 Comments

Using JSON.stringify() with javascript objects containing arrays have a little thing to it. Please check my question: stackoverflow.com/questions/25423883/…
@uylmz I don’t think this bug exists anymore in 2023.
51

Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js, include it and do

var json_data = JSON.stringify(obj);

2 Comments

Should I really need to include "json2.js"? It seems to works without it.
@PavelAlexeev No, you don't neet to include 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.
4

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.
0

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}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.