JavaScript・Working with outside data

JSON: the shape data travels in

Almost all data on the web travels as JSON. Why it looks just like an object yet isn't one, and the two commands that move between text and values.

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
}
RuleHow it differs from an object
Keys must be in double quotesAn object accepts name:
Text uses double quotes onlySingle quotes are invalid
No trailing commaAn object allows one
No commentsNeither // nor /* */
No functionsOnly 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.

As text you can’t reach .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.

JavaScriptMaking the browser remember: localStorageWhere stringify and parse pair up for storage, in this lesson

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);   // 3

data.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

  1. JSON is text that represents data. It resembles an object, but keys and strings need double quotes
  2. Text → value is JSON.parse(), value → text is JSON.stringify()
  3. Read nesting one step at a time, as in data.weather.today

Try it

The “JSON” you learned today is not used on Shima’s page (everything shown there is written straight into the HTML). It’s a tool for pages that display data fetched from elsewhere, like weather or news. Keep it in mind and use it when you need it.

FAQ

What's the difference between JSON and a JavaScript object?
JSON is text that represents data; an object is a value inside your program. JSON has stricter rules: keys must be in double quotes, and trailing commas and comments aren't allowed.
When do I use JSON.parse versus JSON.stringify?
JSON.parse turns received text into something your program can work with. JSON.stringify does the reverse, turning a value into text you can send or store.
Why do I get "Unexpected token"?
Because something breaks JSON's rules. Usually single quotes instead of double, a leftover trailing comma, or an HTML error page arriving where you expected JSON.