30 Days Of JavaScript

Day 14: Strings and JSON

Lesson 5: JSON

JSON stands for "JavaScript Object Notation" and it has become the defacto way of representing structure in a portable way. You are already pretty well versed in JSON because you have been using JavaScript objects since the first couple of days on this course. There are a couple of extra rules for JSON in comparison to "live" JavaScript objects, but really it's just a slightly more strict version.

Here is a JavaScript object as we would write it in code:

1const car = {
2  make: "Nissan",
3  model: "GTR",
4  transmission: "manual",
5  familyFriendly: false,
6  gears: 6,
7};

And here is is the equivalent in JSON.

1{
2  "make": "Nissan",
3  "model": "GTR",
4  "transmission": "manual",
5  "familyFriendly": false,
6  "gears": 6
7}

The main difference being that all the keys need to be wrapped in double quotes and since it's just a notation, there's no concept of assigning the object to a variable or constant. You can literally take that second code block, put it in a file and save it as "car.json" and it it valid.

Just like normal objects in JavaScript, you can have objects stored against properties.

1{
2  "make": "Nissan",
3  "model": "GTR",
4  "transmission": "manual",
5  "familyFriendly": false,
6  "gears": 6,
7  "safetyFeatures": {
8    "airbags": true,
9    "seatbelt": true,
10    "emergencyBreaking": false
11  }
12}

You can also represent arrays in JSON just like you can in JavaScript. Here's an array of cars.

1[
2  {
3    "make": "Nissan",
4    "model": "GTR",
5    "transmission": "manual",
6    "familyFriendly": false,
7    "gears": 6
8  },
9  {
10    "make": "Nissan",
11    "model": "Rogue",
12    "transmission": "automatic",
13    "familyFriendly": true,
14    "gears": 5
15  }
16]

Now, for where this ties into strings. You see when we save data to disc or send it over the internet we do so as text. It doesn't matter how complicated our object is, we want to take it from this:

1const car = {
2  make: "Nissan",
3  model: "GTR",
4  transmission: "manual",
5  familyFriendly: false,
6  gears: 6,
7};

Then save it as string in the most portable and readable way. JavaScript provides us two great methods to do this.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co