JavaScript lesson · 17 min

JavaScript JSON

Parse JSON text into JavaScript data, update it, and serialize it back into a string.

Code runs locally in your browser

What you will practice

  • Understand JSON as a text data format.
  • Use JSON.parse to read JSON.
  • Use JSON.stringify to create JSON text.

What this means

JSON is a text format for structured data. It looks a lot like JavaScript objects and arrays, but it is still text until you parse it.

`JSON.parse` turns JSON text into JavaScript values you can work with. `JSON.stringify` turns JavaScript values back into JSON text.

APIs commonly send JSON because it is compact, readable enough for humans, and easy for many programming languages to understand.

If this is your first time seeing this

JSON is text that follows strict data rules. It may look like JavaScript, but it is not usable as JavaScript data until you parse it.

Think of JSON as a message format between systems.

Mini glossary

JSON
A text format for structured data.
parse
Convert JSON text into JavaScript values.
stringify
Convert JavaScript values into JSON text.

Example from everyday life

JSON is like a shipping label for data. It packages information in a standard format so another app, server, or browser can unpack it and understand what each part means.

How it works step by step

  1. The code starts with JSON text that describes a small project.
  2. `JSON.parse` converts the text into a JavaScript object.
  3. The code reads the project name and updates the `tools` array.
  4. `JSON.stringify` converts the updated object back into JSON text.

Where you will use this

  • A frontend app receives product data from an API as JSON.
  • A browser tool stores settings as JSON text in local storage.
  • A webhook sends event data to another service as JSON.

Before you run the code

The important distinction is text versus data. JSON text must be parsed before you can safely access properties like `data.name`.

When JSON is invalid, parsing fails. That is why JSON formatters and validators are useful in everyday development.

Common beginner mistakes

  • Forgetting quotes around JSON property names.
  • Leaving a trailing comma at the end of a JSON object or array.
  • Trying to access properties before calling `JSON.parse`.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingReads data parsed from JSON
WaitingUpdates and prints the tools array

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Add another item to the `tools` array before stringifying.
  • Break the JSON on purpose and see the error.
  • Use `JSON.stringify(data, null, 2)` to print pretty JSON.