# Operating on JSON: JSON.parse and JSON.stringify

Salesforce Certified JavaScript Developer I · lesson 6

Six rules cover almost every JSON question.

Video: https://www.youtube.com/watch?v=25cRamnGB30
Page: https://shipitcertified.com/learn/salesforce-javascript-developer/json-parse-and-stringify/
Free slide PDF (free account): https://shipitcertified.com/learn/salesforce-javascript-developer/json-parse-and-stringify/

## Chapters

- 0:00 [Operating on JSON: parse and stringify](https://www.youtube.com/watch?v=25cRamnGB30)
- 0:36 [Quick recap: arrays and their methods](https://www.youtube.com/watch?v=25cRamnGB30&t=36s)
- 1:14 [Six rules cover almost every JSON question](https://www.youtube.com/watch?v=25cRamnGB30&t=74s)
- 1:56 [One table holds the whole lesson](https://www.youtube.com/watch?v=25cRamnGB30&t=116s)
- 3:01 [parse reads JSON text; stringify writes it](https://www.youtube.com/watch?v=25cRamnGB30&t=181s)
- 4:00 [Invalid JSON text throws a SyntaxError](https://www.youtube.com/watch?v=25cRamnGB30&t=240s)
- 5:01 [stringify drops or changes what JSON cannot say](https://www.youtube.com/watch?v=25cRamnGB30&t=301s)
- 6:04 [The round trip is not lossless](https://www.youtube.com/watch?v=25cRamnGB30&t=364s)
- 6:46 [A circular reference makes stringify throw](https://www.youtube.com/watch?v=25cRamnGB30&t=406s)
- 7:26 [A replacer filters what stringify writes](https://www.youtube.com/watch?v=25cRamnGB30&t=446s)
- 8:33 [toJSON and space shape the output text](https://www.youtube.com/watch?v=25cRamnGB30&t=513s)
- 9:35 [A reviver rebuilds values while parse runs](https://www.youtube.com/watch?v=25cRamnGB30&t=575s)
- 10:28 [Parsed dates are strings until you revive them](https://www.youtube.com/watch?v=25cRamnGB30&t=628s)
- 11:07 [Large numbers can lose precision](https://www.youtube.com/watch?v=25cRamnGB30&t=667s)
- 11:44 [response.json() returns a promise of the parsed body](https://www.youtube.com/watch?v=25cRamnGB30&t=704s)
- 12:40 [Deep copy: JSON round trip against structuredClone](https://www.youtube.com/watch?v=25cRamnGB30&t=760s)
- 13:23 [Six terms to say in your own words](https://www.youtube.com/watch?v=25cRamnGB30&t=803s)
- 14:03 [Round-trip an object, then list what changed](https://www.youtube.com/watch?v=25cRamnGB30&t=843s)
- 14:56 [Eight questions, closed book](https://www.youtube.com/watch?v=25cRamnGB30&t=896s)
- 16:00 [A developer runs the following code. What is logged?](https://www.youtube.com/watch?v=25cRamnGB30&t=960s)
- 16:42 [{"c":null}](https://www.youtube.com/watch?v=25cRamnGB30&t=1002s)
- 17:42 [Four rules for JSON](https://www.youtube.com/watch?v=25cRamnGB30&t=1062s)
- 18:17 [Now test it, then move to functions](https://www.youtube.com/watch?v=25cRamnGB30&t=1097s)

## Transcript

### Operating on JSON: parse and stringify (0:00)

Welcome to module one, lesson six: operating on json, with json dot parse and json dot stringify. This module is called Variables, Types, and Collections, and it carries twenty three percent of the exam. Json is how data crosses the network, and the exam asks what survives the trip. We cover three things: json dot parse, json dot stringify, and response dot json. By the end, you will be able to predict what a json round trip keeps, drops, and changes, and spot the trap before you run it.

### Quick recap: arrays and their methods (0:36)

Before we start, a quick recap from lesson five, on arrays and their methods. First, some array methods mutate the array in place, and others return a new one. Second, the default sort compares text, so it is not numeric unless you pass a compare function. Third, map transforms every item, and reduce folds the array into one value, each with its own return value. And fourth, our rhythm in every lesson is rule, trace, trap, proof. Today the data leaves the program as text. We turn data into json text, and back again.

### Six rules cover almost every JSON question (1:14)

This domain is twenty three percent of the exam. This lesson boils down to six rules, and two methods: parse and stringify. Rule one: parse and stringify, the two directions of the conversion. Rule two: json syntax is strict. Rule three: what stringify drops. Rule four: the replacer, the space argument, and the "to json" method. Rule five: the reviver. And rule six: response dot json, and deep copying. Rules two and three produce most of the questions, so we slow down there. We will also cover circular references and large numbers.

### One table holds the whole lesson (1:56)

This is the foundations slide, and one table holds the whole lesson. Every remaining slide is one row of this table, with an example, so pause here and read each row aloud. Parse. The rule: text goes in, and a value comes out. The trap is that invalid json throws a "syntax error". The safe habit is a try catch around it. Stringify. The rule: a value goes in, and text comes out. The trap is that it drops undefined and functions without telling you. The safe habit is to check the output. Replacer and reviver. The rule: filter on the way out, and rebuild on the way in. The trap is that dates come back as strings. The safe habit is to use a reviver. Deep copy. The rule: "structured clone" keeps dates and handles cycles. The trap is that a json round trip loses types. The safe habit is to prefer "structured clone". The practical rule: json is text, and anything json cannot say is dropped or changed.

### parse reads JSON text; stringify writes it (3:01)

Rule one. Json dot parse reads json text, and json dot stringify writes it. Look at the code. We start with a student object: a name, an age, a list of courses, and a spouse that is null. Json dot stringify of the student gives one string of json text, with every key and every string in double quotes. Then json dot parse of that text gives the object back, so the courses at index one is the string css. Json is a namespace object, not a constructor. It holds objects, arrays, strings, numbers, booleans, and null. And to read a field from json text, you parse first, and then use dot or bracket access. Writing the new keyword before json would fail, because json is not a constructor. And strings and keys need double quotes. The exam point: to read a field from a json string, json dot parse it first.

### Invalid JSON text throws a SyntaxError (4:00)

Rule two. Json syntax is strict, and invalid json text throws a "syntax error". Look at the code. First, json dot parse of text with single quotes throws a "syntax error", because json needs double quotes. Second, a trailing comma throws a "syntax error" too. Third, nan is not json, so that throws as well. Only the last one works: the value null is valid json, and parse gives back an object with a set to null. So property names and strings need double quotes. There are no trailing commas and no comments. Undefined, nan, and Infinity are not valid json. And untrusted input belongs in a try catch. The trap is thinking json is just a JavaScript object literal. A literal is more forgiving than json: single quotes and trailing commas work in code, but not in json text. The exam point: invalid json text passed to json dot parse throws a "syntax error".

### stringify drops or changes what JSON cannot say (5:01)

Rule three. Stringify drops or changes whatever json cannot say. This is where most of the questions live. Look at the code. In the first call, the object has a set to undefined, b set to a function, and c set to nan. The result keeps only c, and c is null. In the second call, an array holding undefined and nan gives an array of two nulls. And in the third call, a "big int" value makes stringify throw a "type error". So in objects, undefined, functions, and symbols are omitted. In arrays, they become null. Nan and Infinity become null, and are never omitted. And symbol keys are skipped, while a "big int" throws a "type error". Position matters. Inside an object the key vanishes. Inside an array the slot stays, so it becomes null. The exam point: undefined and nan in an array give an array of two nulls, while an object with a set to undefined gives empty curly braces.

### The round trip is not lossless (6:04)

Now the trap. The round trip is not lossless. The wrong shortcut says everything survives stringify. The correct exam test is to ask what json can express: omitted in objects, null in arrays. Look at the code. This object has undefined, a function, nan, and an array holding undefined. Stringify gives c as null, and d as an array with one null. And an object with only an undefined value gives empty braces. Missing keys are silent. Nothing throws, so the bug hides. The practical rule: stringify then parse is a copy of only the json safe part.

### A circular reference makes stringify throw (6:46)

Another way stringify fails: a circular reference. Look at the code. We make an object, and then set its self property to the object itself. Stringify of that object throws a "type error". An object that refers to itself cannot be stringified. The message text differs between engines, so test for the error type, a "type error", not the message. And "structured clone" copes with cycles, while json does not. Do not rely on the message wording. The error type is what is stable. The exam point: o dot self equals o, then json dot stringify of o, throws a "type error".

### A replacer filters what stringify writes (7:26)

Rule four. Stringify takes more arguments than the value: a replacer, and a space. First the replacer, which filters what stringify writes. Look at the code. A user has a name, a password, and an age. We do not want to send the password. Passing an array of names, name and age, keeps only those keys. The result has name and age and no password. A function does the same job. It runs for each key and value, and when the key is password it returns undefined, so that key is omitted. Otherwise it returns the value unchanged. Same result. An array keeps only the listed names, at every level. A function runs for each key and value, and returning undefined omits it. The first call uses the empty key, for the whole object. And return the value unchanged to keep it. For an object with a and b, a logging replacer sees the empty key first, then a, then b. The exam point: the keys a function replacer sees are the empty string, then a, then b.

### toJSON and space shape the output text (8:33)

Two more ways to shape the output text: the "to json" method, and the space argument. Look at the code. A room object has a number, twenty three, and a "to json" method that returns that number. When we stringify an object containing the room, stringify calls "to json" and writes what it returns. So room becomes twenty three in the text. A Date works this way too. A date has a "to json" method, the same as "to I S O string", so the date becomes an I S O string in quotes. Last, the third argument, space, adds indentation. Here we pass null for the replacer, because we only want the indentation, and two for two spaces. So if a value has a "to json" method, its return value is serialized. Date has one. The third argument adds indentation. And use space for display, not for transmission. The exam point: a Date goes into json as an I S O string.

### A reviver rebuilds values while parse runs (9:35)

Rule five. Parse takes a second argument too: a reviver, which rebuilds values while parse runs. Look at the code. This text has a title and a date, and the date is an I S O string. We pass parse a function with two parameters, key and value. When the key is date, it returns a new Date made from the value. Otherwise it returns the value unchanged. So meetup dot date is a real Date, and calling "get date" on it works. The reviver is called for each key and value pair, and its return value replaces the value. Returning undefined deletes the property. So return the other values unchanged, or they are deleted. Remember that stringified dates come back from parse as strings, not Date objects. The exam point: use a reviver to restore Date objects after json dot parse.

### Parsed dates are strings until you revive them (10:28)

Now the trap. Parsed dates are strings until you revive them. The wrong shortcut says parse gives back the same object. The correct exam test: dates return as strings, and a reviver that returns undefined deletes the key. Look at the code. We parse an object with a and b, and the reviver returns undefined when the key is a. The result is an object with only b, equal to two. Replacer omits on the way out; reviver deletes on the way in. Both treat undefined as remove. The practical rule: a reviver must return every value it does not change.

### Large numbers can lose precision (11:07)

Large numbers can lose precision. A json number can have any precision, but a JavaScript number is fixed precision floating point. Json dot parse converts numbers before the reviver runs, so precision may already be lost by the time your function sees the value. The reviver does get an extra argument, context, and its source property gives the original text of the number. If the receiver cannot hold the number, send it as a string instead. Not every json number fits in a JavaScript number. The practical rule: serialize very large numbers as strings, and handle them as strings.

### response.json() returns a promise of the parsed body (11:44)

Rule six. When data arrives from a server, response dot json does the parsing for you, and it returns a promise of the parsed body. Look at the code. We call fetch inside a try block, and await the response. Next we check response dot ok. If it is false, we throw our own error with the status. Only then do we await response dot json, and log the result. And the catch block reports the error message. So await it, or chain dot then. Fetch does not reject on a four oh four, so check response dot ok. Invalid json makes json throw, and the body reads only once, so use clone to read it twice. And the result is a JavaScript value, not json text. Despite the name, json gives you an object, array, string, or number. The exam point: await response dot json, after checking response dot ok.

### Deep copy: JSON round trip against structuredClone (12:40)

One more use of json: a deep copy. Compare the json round trip, stringify then parse, against "structured clone". Circular references first. The round trip throws a "type error". Structured clone supports them. A Date: through the round trip, it becomes a string. With "structured clone", it stays a Date. A function property: the round trip silently drops it. "structured clone" throws a "data clone error". So the code is one line: copy equals "structured clone" of original. It is deep, keeps Date, and handles cycles. The exam point: "structured clone" handles cycles and keeps Date, but throws on functions.

### Six terms to say in your own words (13:23)

Six terms to say in your own words. Json dot parse converts json text to a value, and throws a "syntax error" if the text is invalid. Json dot stringify converts a value to json text. A replacer is an array of keys or a function that filters stringify. The "to json" method supplies a value's serialized form. A reviver is a function passed to parse that transforms values as they are parsed. And "structured clone" is a deep clone that supports cycles and throws on functions. Pause the video now. Cover each card and explain the term aloud.

### Round-trip an object, then list what changed (14:03)

Now the proof stage, starting with a lab. Round-trip an object, then list what changed. Look at the code. The original has a name, a date, a note set to undefined, a greet function, a tags array holding a string and undefined, and stats with a score of nan and an n of one. Then copy is the parse of the stringify of the original. Predict first, on paper, what changed in the copy. Then run it in Node, and match each change to a rule. This is the lab from the curriculum. Take a few minutes on your own. Now the answers. The date is now a string, in I S O format. The note is gone. The greet function is gone. The tags array is now a, and null. And the score is null. A wrong prediction is the lesson. Go back to the slide that explains it.

### Eight questions, closed book (14:56)

Self check: eight questions, closed book. Answer out loud, then I will reveal each one. One. What does json dot parse do with single quotes? It throws a "syntax error". Two. What is stringify of an object whose only value is undefined? The text, empty braces. Three. What is stringify of an array holding undefined and nan? The text, an array of two nulls. Four. An object points to itself, then we stringify it. It throws a "type error". Five. Stringify of a user with the array name only: what is kept? Only name. Six. What is the first key a function replacer sees? The empty string. Seven. What is a Date after json dot parse? A string. And eight. What does await response dot json give you? The parsed value. How many did you get? Anything you missed, go back to its slide.

### A developer runs the following code. What is logged? (16:00)

Time for a practice question, taken from the question bank. This is a predict question. Pause the video and trace each property before you read the options. A developer runs the code shown. What is logged? Option A: curly braces, with a null, b null, and c null. Option B: empty curly braces. Option C: curly braces, with c set to nan. Option D: curly braces, with c set to null. This question combines the stringify rules from this lesson. Work through the three properties one at a time. Pause now, and I will give you the answer on the next slide.

### {"c":null} (16:42)

The answer is D. Curly braces, with c set to null. Here is why. Property a is undefined, and in an object an undefined value is omitted. Property b is a function, and functions in an object are omitted too. Property c is nan, which is not valid json, so stringify writes null. Only c survives. Now the wrong options. A says a, b, and c are all null. That thinks the dropped values turn into null, but that only happens inside arrays. B says empty braces. That thinks nan is dropped too, but nan is not omitted: it becomes null, so c survives. C says c is nan. That thinks nan is written as is, but nan is not valid json, so stringify writes null instead. The takeaway: in objects, undefined and functions vanish, and nan becomes null.

### Four rules for JSON (17:42)

Four rules for json, in one place. Parse: double quotes only, invalid text throws a "syntax error", and a reviver rebuilds Dates. Stringify: it omits undefined and functions in objects, and writes null in arrays. Nan becomes null. Throws: circular references and "big int" values throw a "type error". Copy: "structured clone" keeps Date and cycles, and the json round trip does not. Remember: await response dot json, after checking response dot ok.

### Now test it, then move to functions (18:17)

That completes lesson six, and with it the module on variables, types, and collections. Now test it, then move to functions. The flow is: read it, predict it, test it. Your practice set is this lesson's questions in the bank. Do them now, closed book, and map any miss back to the slide that explains it. In the next lesson, Choosing the Best Function Implementation, we start the functions module. See you there.
