In this example, we're including expect from npm, and also Gandalf is telling us that we can't parse. But we're going to prove him wrong.
Here we have our input for our test. This is a JSON string that we'll be parsing for our test. It's an array of book objects.
Now, let's use the basic API JSON.parse, and we'll pass our input string and comment out the other test call. Now if we run the test, we'll see that our test passed.
If we put in the string "true", it will actually result in a Boolean value of true. We can also put in the string "3", which will result in the number three. Or the string "Hello, World!", which will result in a string "Hello, World!"
All of this is valid JSON. If we provide invalid JSON, the browser will throw a syntax error. So, that's the basic use of the API.
One part of the JSON parse API that is less commonly used is the second argument, which is called a reviver function. This is used to instruct JSON parse how to parse certain values of our JSON string.
For this test, our expected is slightly different. The publish date key in the first example was simply a string, and in this example we want the parse API to convert it to a Date object automatically for us.
To do this, we'll call JSON parse with our input again. This time, we'll add a reference to a function we'll create called reviver. We'll add that down here. It accepts a key and a value. Let's go ahead and just console.log our key and value, then return the value.
Looking at the output we'll see the key of ID and the value of 1. So, there's that. Title is "Gone with the Wind", publish date, etc, etc. Then, at the very end, we'll get that the key is an empty string, and that the value is the entire entity that's being parsed. In our case, that's the entire array.
It's important to remember to handle this case for the empty string key. Generally, you'll simply return the value. If you return anything else, then that's what comes back from the call to JSON.parse.
For example, if we return an empty object, that's what you'll see. Or, if you return a string of "Hello, World!", then that's what's going to be returned. For our case, we'll simply return the value.
The next thing we want to handle is when the key is publish date. In this case, we'll return a new Date for the value. This gets our test passing. If we add a console.log of the result, we'll see that we get an array of items where the publish date property is a Date object.
To recap, you'll simply call JSON.parse with the valid JSON string you want to parse. Then you can pass a reviver function, which accepts a key and a value, and returns the value you want used for that position in the object.
One final thing to note that wasn't covered in our example is the context of a reviver function. If we console.log key and this, we'll see that this is bound to where the key and value is coming from.
That's the JSON parse API.