I have tried a number of methods that are suggested for similar sounding problems but I can’t get them to work….
I am trying to get output from a JSON call into a data frame, but I can’t find a way to manipulate the list – it looks as though it should be easy, but all the solutions proposed seem very complicated and I can’t get them to work.
An example of the call is:
res = GET("https://vpic.nhtsa.dot.gov/api/vehicles?Year=2011&Make=Acura&Model=&units=US&format=json")
data = fromJSON(rawToChar(res$content), flatten = TRUE)
R<-data$Results
S<-R$Specs
This then gives me a list of 9 data frames, each with a Name column and a Value column
The Name column is repeated exactly in each data frame
I simply want to get these into a single data frame with the Name column providing column names and the Value columns from each data frame as individual rows.
Any suggestions gratefully received – many thanks.
2
Answers
You need to extract each
Name
andValue
pair and then bind them together. For one row you can do this:Or to apply this to your entire result.
Alternative to
jsonlite::read_json()
I do not know why
read_json()
would give you an error as it seems to work when I use it. However, you can also get theres
object by doing:Then the rest of the code is the same.
Here is another approach using
rrapply()
(in packagerrapply
) to unnest the nested list to a long data.frame and then usingunstack()
to transform from a long to a wide data.frame: