Getting ready

JSON was created at a time when most web communication was done by sending XML over browser plugins such as Java or Flash. This was cumbersome and made the exchanged information quite bloated. Douglas Crockford, the creator of JSLint and author of the famous JavaScript: The Good Parts, decided in the early 2000s that it was time for a lightweight format that was easily integrated with JavaScript. He oriented himself on a small subset of JavaScript, namely the way it defined objects, and extended it a little bit to form the JavaScript Object Notation or JSON. Yes, you've read that right; JSON is not a subset of JavaScript, as it accepts things that JavaScript doesn't. You can read more about that at http://timelessrepo.com/json-isnt-a-javascript-subset.

The sad irony of the story is that today we have gone full-circle: our best practices for web development include a labyrinth of task runners, frameworks, and transpilers, which are all quite nice in theory but end up being a giant bloated mess in the end. But that is a story for another time.

JSON is built upon two structures:

  • A group of key-value pairs surrounded by { and }, which is called an object and can be a value itself
  • A list of values surrounded by [ and ] called an array

This might remind you a bit of the TOML syntax we discussed earlier, and you might ask yourself when you should prefer one over the other. The answer is that JSON is a good format when your data is going to be read automatically by a tool, while TOML is excellent when your data is meant to be read and modified manually by a human.

Take note that one thing that JSON doesn't allow is comments. This makes sense, as comments are not readable by tools anyway.

An example of a JSON object with values, sub-objects, and arrays could be the following:

{
name: "John",
age: 23,
pets: [
{
name: "Sparky",
species: "Dog",
age: 2
},
{
name: "Speedy",
species: "Turtle",
age: 47,
colour: "Green"
},
{
name: "Meows",
species: "Cat",
colour: "Orange"
}
]
}

We are going to write and read this exact example in the following code. The definitions of the pets are intentionally inconsistent because many web APIs omit certain keys in some situations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.44.182