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

Example 1Try it yourself
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

Example 2Try it yourself
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?

  1. JSON.parse()
  2. JSON.stringify()
  3. Object.toJSON()
  4. String()
Show answer

Answer: JSON.stringify()

Practice next