JSON
When you open a website, your browser asks a server for it. A server is a computer on the internet that keeps the files of a website and sends them to anyone who asks. First it sends index.html, and then the styles, pictures and scripts that the page needs.
A script on the page can ask the server for something too: not a whole page, just data. An online shop asks for its products, a chat for new messages, a weather app for the forecast. The page stays the same, and only the data changes. That's how one page can show thousands of different products.
The data travels as text, most often in a format called JSON (short for JavaScript Object Notation, and said like the name Jason). Files with data in JSON end in .json. Here's a list of the animals in a small animal shelter:
[
{ "name": "Rex", "species": "dog", "age": 3, "vaccinated": true },
{ "name": "Luna", "species": "cat", "age": 2, "vaccinated": false }
]It looks just like an array of objects in JavaScript, and that's where the name comes from. But JSON has stricter rules:
- Keys are always in double quotes:
"name", notname. - Text is in double quotes too. Single quotes, as in
'Rex', aren't allowed. - There's no comma after the last item of an array or the last property of an object.
- There are no comments, variables or functions. The values are text, numbers,
true,false,null, arrays and objects.
A single mistake, and the browser can't read the file at all. In the console, it then reports a SyntaxError that says where it got stuck: the line and column, or the text around the mistake.
The exercises have no real server, but the preview acts as one: a script can ask for any file of the exercise and gets it after a short moment, as if from a server on the internet. In this exercise, the script is ready: it asks for animals.json and shows the animals in a list. How it does that is the topic of the exercise after next. For now, you'll work only with the data, in the file animals.json.
Instructions
The page shows only Loading…, because animals.json has mistakes: the last animal, Max, is written the way you write objects in JavaScript. Fix it so that it follows the rules of JSON, and the page shows all three animals.
The shelter has a new animal: the cat Mia, 2 years old and vaccinated. Add her to the end of the array, with the same four properties as the other animals. Write the age as a number and true without quotes, as the others have them.