Working with Json file

R may be not the best software to handle JSON files. But for those want to insist on using R instead of Python or some other programs, let see how to work with JSON files.


Read JSON file

The example used here is from https://support.oneskyapp.com/hc/en-us/articles/208047697-JSON-sample-files

lets use a simple JSON file

{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red"
}

In R data is normally handled using data frames. 
So lets convert the JSON to data frame.
The package used to do that is ‘jsonlite’. 

The code
library(jsonlite)
# point the location of the file
json_file1 <-"C:\\data\\rblog\\example_1.json"
# read the file using fronJSON function
json_data1 <- fromJSON(json_file,  flatten = FALSE  )





# convert to data frame
json_data_frame1 <- data.frame(json_data)




More complicated JSON files cannot be handled in the same method.
Lets look at the second example.
json_file2 <-"C:\\data\\rblog\\example_2.json"
json_data2 <- fromJSON(json_file2, flatten = FALSE)




Up to this point no issue, but when try to convert to dataframe, the following error occurs.
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
  arguments imply differing number of rows: 1, 0, 801, 684, 60

The reason is very clear, the data contains the lists of different length and dataframe.
But it is possible to create separate  dataframes.



For example,
json_data_frame3 <- data.frame(json_data2$afmlist)