I have a JSON data source that is a list of objects. Some of the properties of the object are themselves lists. I want to turn all this into a data frame, save lists as values of a data frame .
Sample JSON data:
[{
"id": "A",
"p1": [1, 2, 3],
"p2": "foo"
},{
"id": "B",
"p1": [4, 5, 6],
"p2": "bar"
}]
Required data frame:
id p2 p1
1 A foo 1, 2, 3
2 B bar 4, 5, 6
Failed Attempt 1
I found this pretty easy way to parse my JSON:
unlisted_data <- lapply(fromJSON(json_str), function(x){unlist(x)})
data.frame(do.call("rbind", unlisted_data))
However, the unlisting process extends my duplicate value to multiple columns:
id p11 p12 p13 p2
1 A 1 2 3 foo
2 B 4 5 6 bar
I expected the call unlistwith the option to recursive = FALSEtake care of this, but that is not the case.
Failed to try 2
I noticed that I can almost do this with a function I:
> data.frame(I(parsed_json[[1]]))
parsed_json..1..
id A
p1 1, 2, 3
p2 foo
. :
> t(data.frame(I(parsed_json[[1]])))
id p1 p2
parsed_json..1.. "A" Numeric,3 "foo"