JavaScript Tutorial · Objects and Arrays · Lesson 27 of 44
JavaScript JSON
Convert objects to JSON strings and parse JSON back into objects.
What is JSON?
JSON (JavaScript Object Notation) is the standard text format for exchanging data between servers and apps. It looks like JavaScript objects, with stricter rules: keys must be double-quoted strings, and values can only be strings, numbers, booleans, null, arrays and objects.
JSON.stringify — object to text
const user = { name: "Ada", skills: ["js", "sql"], active: true, greet() {} };
const text = JSON.stringify(user);
console.log(text);
console.log(typeof text);
console.log(JSON.stringify({ id: 1, tags: ["a"] }, null, 2));
Output
{"name":"Ada","skills":["js","sql"],"active":true}
string
{
"id": 1,
"tags": [
"a"
]
}The third argument pretty-prints with indentation. Functions and undefined values are skipped.
JSON.parse — text to object
const response = '{"id": 42, "title": "Learn JSON", "done": false}';
const todo = JSON.parse(response);
console.log(todo.title, todo.done);
try {
JSON.parse("{name: 'Ada'}");
} catch (err) {
console.log("Invalid JSON:", err.name);
}
Output
Learn JSON false Invalid JSON: SyntaxError
Invalid JSON throws a SyntaxError, so wrap JSON.parse in try...catch when the input comes from outside your code.
Test yourself
Which method turns a JavaScript object into a JSON string?
JSON.parse()JSON.stringify()Object.toJSON()String()
Show answer
Answer: JSON.stringify()
Practice next
- Flatten Nested JSON · coding problem