JavaScript JSON: Parse and Stringify Data
JSON is a text format used to exchange structured data. JavaScript provides built-in methods to convert between JSON text and JavaScript values.
Quick answer: Use JSON.parse(text) to turn valid JSON text into a JavaScript value. Use JSON.stringify(value) to convert a serializable JavaScript value into JSON text.
Read JSON text with JSON.parse()
JSON often arrives from a file, form, or web response as text. Parse it before accessing its properties.
const jsonText = '{"title":"Learn JavaScript","lessons":8}';
const course = JSON.parse(jsonText);
console.log(course.title); // "Learn JavaScript"
console.log(course.lessons); // 8
JSON uses double-quoted property names and string values. It supports objects, arrays, strings, numbers, booleans, and null; it does not support JavaScript comments or functions.
Create JSON text with JSON.stringify()
When sending or storing data, stringify a JavaScript object or array to get JSON text.
const settings = {
theme: "light",
fontSize: 16
};
const settingsText = JSON.stringify(settings);
console.log(settingsText);
// {"theme":"light","fontSize":16}
You can pass spacing as a third argument to format JSON for reading:
const readableText = JSON.stringify(settings, null, 2);
Handle invalid JSON safely
JSON.parse() throws a SyntaxError when the input is not valid JSON. When text comes from an external source, catch the error and decide how your app should respond.
function readJson(text) {
try {
return JSON.parse(text);
} catch (error) {
console.error("Could not read the JSON data.", error);
return null;
}
}
Validate the parsed value too. Valid JSON can still have a different shape than your page expects, such as a missing title property.
JSON and JavaScript objects are different
A JavaScript object is a value your code can work with. JSON is text with a defined syntax. Converting with stringify() does not preserve every JavaScript value; functions and some unsupported values are omitted or represented differently.
JavaScript JSON questions
Can JSON contain comments?
No. Standard JSON does not allow comments, trailing commas, or single-quoted strings. Remove these before parsing the text.
When does JSON.parse() fail?
It fails when the input string does not follow JSON syntax. Use try...catch for untrusted or external text, then validate the resulting data before relying on it.
Practice: save and restore settings
Create a settings object with a theme and text size. Convert it to text with JSON.stringify(), then parse the text back and display one of its values. Change a quote or add a trailing comma and use your error handler to see how invalid JSON is handled.