JSON: Objects as Text

Grade 8, page 11 of 13. A one-minute read.

Objects live in your program's memory. But what if you want to save an object to a file, or send it across the internet to another computer? You need to turn it into text. The standard format for this is called JSON (pronounced "Jason"), which stands for JavaScript Object Notation.

JSON looks almost exactly like a JavaScript object, with a few stricter rules: all keys must be in double quotes, strings must use double quotes, and you can't include functions or trailing commas.

JavaScript has a built-in JSON object with two methods:

  • JSON.stringify(obj) turns an object into a JSON string.
  • JSON.parse(text) turns a JSON string back into an object.
JavaScript
const player = { name: "Mia", level: 7, items: ["sword", "shield"] };

const text = JSON.stringify(player);
console.log(text);
console.log(typeof text);

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

const backAgain = JSON.parse(text);
console.log(backAgain.items[0]);

It prints

{"name":"Mia","level":7,"items":["sword","shield"]}
string
{
  "name": "Mia",
  "level": 7,
  "items": [
    "sword",
    "shield"
  ]
}
sword

The null, 2 in the middle example tells stringify to make it pretty, with 2 spaces of indentation. (The null is a slot for an advanced option that we don't need.)

JSON is the language that the internet speaks. When you load weather data, news articles, or a list of products from a server, it almost always arrives as JSON. You'll use JSON.parse in Grade 12 to save data in the browser, and again in College to fetch data from the internet.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning