Complete JavaScript Course Module 7: Intermediate: Objects and JSON

Working with JSON in JavaScript

  • Beginner
  • Lesson 7.5
  • 5 min read
  • 31 of 76 in the course

In short

JSON is a text format for storing and sending data. Learn how to convert JavaScript objects to JSON with JSON.stringify and back with JSON.parse, and handle errors. What is JSON? JSON stands for JavaScript Object Notation.

JSON is a text format for storing and sending data. Learn how to convert JavaScript objects to JSON with JSON.stringify and back with JSON.parse, and handle errors.

What is JSON?

JSON stands for JavaScript Object Notation. It is a way to write data as plain text, using a syntax that looks very much like JavaScript objects and arrays.

Why do we need it? Computers often send data to each other over the internet, and they can only send text. JSON is like a shipping box: you pack your object into text, send it, and the other side unpacks it back into data. Almost every programming language can read JSON, so it is the most common data format on the web.

Here is what a JSON text looks like:

{
  "id": 501,
  "name": "Wireless Mouse",
  "price": 24.99,
  "inStock": true,
  "tags": ["electronics", "office"],
  "discount": null
}

What is the difference between JSON and a JavaScript object?

JSON looks like an object literal, but its rules are stricter:

RuleJavaScript objectJSON
KeysQuotes optional: name: "Ana"Must use double quotes: "name": "Ana"
StringsSingle, double or backticksDouble quotes only
Trailing commaAllowedNot allowed
CommentsAllowedNot allowed
Functions, undefinedAllowedNot allowed
Allowed valuesAnythingStrings, numbers, booleans, null, arrays, objects

The biggest difference: a JavaScript object is a value in memory, while JSON is always a string of text.

How to convert an object to JSON with JSON.stringify

JSON.stringify() takes a JavaScript value and returns a JSON string.

const product = {
  name: "Wireless Mouse",
  price: 24.99,
  tags: ["electronics", "office"],
  onSale: undefined,
  describe() {
    return this.name;
  },
};

const json = JSON.stringify(product);
console.log(json);
// Output: {"name":"Wireless Mouse","price":24.99,"tags":["electronics","office"]}
console.log(typeof json);
// Output: string

const pretty = JSON.stringify(product, null, 2);
console.log(pretty);

The pretty version prints:

{
  "name": "Wireless Mouse",
  "price": 24.99,
  "tags": [
    "electronics",
    "office"
  ]
}

Notice that onSale (which is undefined) and the describe method are silently left out, because JSON cannot store them. The third argument, 2, tells JSON.stringify to indent with two spaces. This pretty printing makes JSON much easier for humans to read. The second argument (null here) is an optional filter you can ignore for now.

How to turn JSON back into an object with JSON.parse

JSON.parse() does the opposite: it takes a JSON string and returns a real JavaScript value you can use.

const response = '{"user":"Sara","points":120,"badges":["starter","streak"]}';

const data = JSON.parse(response);
console.log(data.user);           // Output: Sara
console.log(data.points + 10);    // Output: 130
console.log(data.badges.length);  // Output: 2

Before parsing, response is just text, so response.user would be undefined. After parsing, data is a normal object with properties and an array.

Tip: A quick way to copy simple data is JSON.parse(JSON.stringify(obj)), but it loses dates, functions and undefined. In modern code, prefer structuredClone(obj).

Common JSON errors and how to catch them with try/catch

If the text is not valid JSON, JSON.parse throws a SyntaxError and your script stops. This happens a lot with data from outside your code. Typical causes:

  • Single quotes instead of double quotes: {'name': 'Ana'}
  • Keys without quotes: {name: "Ana"}
  • A trailing comma: {"name": "Ana",}
  • An empty string or an HTML error page instead of JSON

To handle this safely, wrap the parse in a try...catch block. Code in try runs normally. If it throws an error, JavaScript jumps to catch instead of crashing. You will learn error handling in detail in a later lesson; here is a preview:

const badJson = "{name: 'Ana'}";

try {
  const user = JSON.parse(badJson);
  console.log(user.name);
} catch (error) {
  console.log("Could not read the data:", error.name);
}
// Output: Could not read the data: SyntaxError

The error message text differs between browsers, but error.name is always "SyntaxError".

Common mistake: Calling JSON.parse on something that is already an object. JSON.parse({ a: 1 }) first turns the object into the text "[object Object]", which is not valid JSON, so it throws. Only parse strings.

Where is JSON used? APIs and localStorage

You will meet JSON in two places very often:

  1. APIs: when your page asks a server for data (like weather or products), the answer usually comes back as JSON. You will learn to fetch data in a later lesson.
  2. localStorage: the browser's built-in storage that keeps data even after the page is closed. It can only store strings, so you save objects with JSON.stringify and read them with JSON.parse.

Here is a small example that saves a cart in localStorage. Run it in the console of any normal web page:

const cart = [
  { id: 1, name: "Notebook", qty: 2 },
  { id: 2, name: "Pen", qty: 5 },
];

localStorage.setItem("cart", JSON.stringify(cart));

const saved = JSON.parse(localStorage.getItem("cart") ?? "[]");
console.log(saved[1].name);
// Output: Pen

setItem stores the JSON text under the key "cart". getItem gives back the text, or null if nothing is saved, so ?? "[]" provides an empty list as a safe fallback. JSON.parse turns it back into an array of objects. If you reload the page and run only the last two lines, the cart is still there.

Note: MDN has a clear guide to working with JSON if you want more examples.

Practice exercise

Build a tiny "user settings" saver.

  1. Create an object settings with theme, language and notifications (a boolean).
  2. Log it as pretty-printed JSON with 2-space indentation.
  3. Save it to localStorage under the key "settings".
  4. Read it back, parse it, and log theme.
  5. Try parsing the invalid string "{theme: dark}" inside try...catch and log a friendly message.

Hint: Use JSON.stringify(settings, null, 2) for step 2 and JSON.parse(localStorage.getItem("settings")) for step 4.

Key takeaways

  • JSON is a text format for data, with strict rules: double quotes, no trailing commas, no comments.
  • JSON.stringify turns a value into a JSON string; add null, 2 for pretty printing.
  • JSON.parse turns a JSON string back into a JavaScript value.
  • Invalid JSON throws a SyntaxError, so wrap risky parsing in try...catch.
  • JSON is used everywhere: API responses and saving data in localStorage.