Weather data, a list of social posts—almost everything exchanged on the web is shaped as JSON. It looks just like an object and yet is not one. Understanding that difference puts you at the door of working with outside data.
JSON is text that represents data
An object is a value you use inside your program. JSON is that value turned into text you can carry around.
// An object (a value in your program)
const shima = { name: "Shima", age: 3 };
// JSON (text)
'{"name": "Shima", "age": 3}'They look alike, but the lower one is a single piece of text. You can’t reach into it with a dot.
JSON’s rules
The rules are stricter than an object’s.
{
"name": "Shima",
"age": 3,
"likes": ["drawing", "ramen"],
"isBird": true
}| Rule | How it differs from an object |
|---|---|
| Keys must be in double quotes | An object accepts name: |
| Text uses double quotes only | Single quotes are invalid |
| No trailing comma | An object allows one |
| No comments | Neither // nor /* */ |
| No functions | Only text, numbers, booleans, arrays, objects, and null |
It’s strict so that every language can read it the same way. Once you see that JavaScript’s conveniences can’t be smuggled in, the rules make sense.
Text → value: JSON.parse
Received JSON goes through JSON.parse() first, which turns it into something your program can use.
const text = '{"name": "Shima", "age": 3}';
const shima = JSON.parse(text);
console.log(shima.name);
console.log(shima.age + 1);After parsing it’s an ordinary object: .name works, and numbers behave like numbers.
.name; once parsed, you can.Value → text: JSON.stringify
Going the other way, JSON.stringify() turns a value into text for sending or storing.
const shima = { name: "Shima", age: 3 };
const text = JSON.stringify(shima);
console.log(text);You get {"name":"Shima","age":3}. The same shape is used when storing in the browser.
Reading nested JSON
Real data is usually nested a few levels deep.
{
"city": "Sapporo",
"weather": {
"today": "snow",
"temp": -3
},
"forecast": ["snow", "cloudy", "sunny"]
}To read it, work left to right.
const data = JSON.parse(text);
console.log(data.city); // Sapporo
console.log(data.weather.today); // snow
console.log(data.forecast[0]); // snow
console.log(data.forecast.length); // 3data.weather.today is “inside data, inside weather, today.” However long the chain looks, it’s one step at a time.
The error you’ll meet
Summary of this lesson
- JSON is text that represents data. It resembles an object, but keys and strings need double quotes
- Text → value is
JSON.parse(), value → text isJSON.stringify() - Read nesting one step at a time, as in
data.weather.today