Get an Array of Values into a Cell within a Dataframe Using Jsonlite Package in R
Last Updated :
12 Jun, 2023
The jsonlite package in R is a powerful tool for working with JSON data. One common task when working with JSON data is extracting specific values from a JSON object and placing them in a data frame.
JSON: JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.
- jsonlite package: A package in R for working with JSON data. It provides flexible, robust, high-performance tools for working with JSON in R.
- data frame: Data frames are a popular way to store and manipulate data in R Programming Language, they are similar to tables in a relational database.
Steps to store an array of values in a cell
- First, you will need to install the jsonlite package if it is not already installed. You can do this by running the command “install.packages(“jsonlite”)” in the R console.
- Next, you will need to load the jsonlite package by running the command “library(jsonlite)” in the R console.
- Then, you will use the fromJSON() function to parse the JSON data into a dataframe.
- After that, you can extract the values you need using the $ operator or the square bracket notation.
- Finally, you can append the extracted values to a new dataframe or an existing one.
Store an Array of Values into a Cell using jsonlite
After loading the jsonlite package we will create some demo json_data. Now as we have a demo JSON dataset we can apply fromJSON function to that data.
R
library (jsonlite)
json_data <- '{ "name" : "John" ,
"age" :30,
"city" : "New York" }'
df <- fromJSON (json_data)
name <- df$name
age <- df$age
new_df <- data.frame (name, age)
print (new_df)
|
Output:
name age
1 John 30
Let’s look at one more a little complex example.
R
library (jsonlite)
df <- data.frame (col1 = c ( "A" , "B" , "C" ),
col2 = NA )
arr <- list ( list (name = "John" , age = 30),
list (name = "Jane" , age = 28))
df[2, "col2" ] <- toJSON (arr)
df
|
Output:
Dataframe created using JSON data
Now let’s try to show an example with nested elements in the in the JSON data.
R
library (jsonlite)
df <- data.frame (col1 = c ( "A" , "B" , "C" ),
col2 = NA )
obj <- list (person = list (name = "John" ,
age = 30),
location = list (city = "New York" ,
country = "USA" ))
df[3, "col2" ] <- toJSON (obj)
df
|
Output:
Nested JSON object
Share your thoughts in the comments
Please Login to comment...