JSON
An object lives in the memory of a running program. When the program ends, the object is gone. To save an object in a file, or to send it to another program over the internet, you first turn it into text. The usual text format for this is JSON (JavaScript Object Notation). It looks almost the same as the objects you write in JavaScript. Almost every language and web service can read and write JSON.
JSON.stringify turns a value into JSON text:
const team = [
{ name: "Alice", dept: "HR" },
{ name: "Bob", dept: "IT" },
];
const text = JSON.stringify(team);
console.log(text);
console.log(typeof text);
Output:
[{"name":"Alice","dept":"HR"},{"name":"Bob","dept":"IT"}]
string
The result is one string. JSON has stricter rules than JavaScript. Keys must always be in double quotes. Some JavaScript values have no JSON form at all. JSON.stringify simply leaves out a property whose value is undefined or a function:
const data = { a: 1, b: undefined, c: "yes" };
console.log(JSON.stringify(data));
console.log(JSON.stringify(data, null, 2));
Output:
{"a":1,"c":"yes"}
{
"a": 1,
"c": "yes"
}
The second line adds two more arguments, null and 2. The 2 means "put each property on its own line, indented by 2 spaces". This is easier for people to read.
JSON.parse does the opposite. It turns JSON text back into a real object that you can use:
const text = '{"name":"Bob","age":41}';
const bob = JSON.parse(text);
console.log(bob.name);
console.log(bob.age + 1);
Output:
Bob
42
After parse, bob.age is a real number, so bob.age + 1 gives 42. Note the single quotes around the text. They let you write the double quotes of JSON inside the string.
If the text is not valid JSON, JSON.parse stops the program with an error. Here the key is missing its double quotes:
JSON.parse("{name: 1}");
Output:
<anonymous_script>:1
{name: 1}
^
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
at JSON.parse (<anonymous>)
at Object.<anonymous> (/box/index.js:1:6)
The Errors section shows how to handle errors like this. Until then, only pass valid JSON to parse.
In the exercise, the input is one line of JSON. Parse it, read from it, and turn an updated copy back into JSON.