1. JSON & jsonlite
In this video, let's dive into the JSON format and the jsonlite package some more.
So, what does a typical JSON look like? I'll try to be short on this.
You have JSON objects, and you have JSON arrays.
2. JSON object
A typical JSON object looks like this. It's unordered collection of name/value pairs. where the name is a string and the value can be a string, a number, boolean, null, another JSON object, or a JSON array.
3. JSON object
Let's convert this JSON to an R string by wrapping it in quotes. I use single quotes here so that I don't have to escape every double quote. Now let's pass this string to jsonlite's fromJSON function, that converts a JSON to R code, and ask for the structure of the result.
The result is a named list in R, which contains the same information. You can also see that the elements have different classes: we have characters, integers and logicals.
4. JSON array
Next, there are also JSON arrays. This is an ordered sequence of zero or more values, like this one.
Calling fromJSON on this JSON structure results in an integer vector.
However, this actually is a simplification, because JSON arrays, just like JSON objects, are heterogeneous; they can contain elements of different types. This JSON array for example, is perfectly valid as well.
Trying to convert this JSON into R, give the following result.
The numbers were coerced to characters, as was the logical value. The null keyword was converted to an NA in R. This had to be done because R vectors can only contain a single basic type, remember?
Both the JSON object as the JSON array can contain other JSON objects and arrays, how would that work?
5. JSON Nesting
Suppose we add some information to the JSON object from before. This time, I formatted the JSON such that it becomes more readable.
We can extend it as follows.
6. JSON Nesting
Let's fromJSON this, and see what we get.
We get a nested named list, makes perfect sense if you ask me.
7. JSON Array of JSON Objects
Finally, let's build an array of JSON objects, of three persons for example, like this.
Wow, this was unexpected. We simply got a data frame. But if you think of it, this is a great mapping. We have three JSON objects, on Frank, Julie and Zach, and they all have the same fields, id and name. This perfectly fits the description of an R data frame. The wonderful thing is that jsonlite deals with all of this for us. There are many more use cases of JSON objects and arrays, but I won't go through each and every one of them.
next to fromJSON,
8. Other jsonlite functions
there are other useful functions in the jsonlite package, such as tojson, to convert r data structures back to json, and prettify and minify, to change how jsons are displayed. you'll learn all about these in the exercises that follow!
If you use the jsonlite package you normally won't be dealing with JSONs directly, but it's good to have a basic level of understanding of them.
9. Let's practice!