A colleague is sending me an Elasticsearch query result (100000's of records, hundreds of attributes) that looks like:
pets_json <- paste0('[{"animal":"cat","attributes":{"intelligence":"medium","noises":[{"noise":"meow","code":4},{"noise":"hiss","code":2}]}},',
'{"animal":"dog","attributes":{"intelligence":"high","noises":{"noise":"bark","code":1}}},',
'{"animal":"snake","attributes":{"intelligence":"low","noises":{"noise":"hiss","code":2}}}]')
There is a redundant key, code
, that I do not need to capture.
I would like to produce a data.frame that looks something like:
animal intelligence noises.bark noises.hiss noises.meow
cat medium 0 1 1
dog high 1 0 0
snake low 0 1 0
I can read in the json, but flatten=TRUE
doesn't completely flatten:
library(jsonlite)
str(df <- fromJSON(txt=pets_json, flatten=TRUE))
# 'data.frame': 3 obs. of 3 variables:
# $ animal : chr "cat" "dog" "snake"
# $ attributes.intelligence: chr "medium" "high" "low"
# $ attributes.noises :List of 3
# ..$ :'data.frame': 2 obs. of 2 variables: \
# .. ..$ noise : chr "meow" "hiss" \
# .. ..$ code: int 4 2 |
# ..$ :List of 2 |
# .. ..$ noise : chr "bark" |- need to remove code and flatten
# .. ..$ code: int 1 |
# ..$ :List of 2 |
# .. ..$ noise : chr "hiss" /
# .. ..$ code: int 2 /
Because the flattening is incomplete I can use this intermediate stage to get rid of the code
unwanted keys before calling another flatten()
, but the only way I know to get rid of the keys is really slow:
for( l in which(sapply(df, is.list)) ){
for( l2 in which(sapply(df[[l]], is.list))){
df[[l]][[l2]]['code'] <- NULL
}
}
( df <- data.frame(flatten(df)) )
# animal attributes.intelligence attributes.noises
# 1 cat medium meow, hiss
# 2 dog high bark
# 3 snake low hiss
And then after that...? I know that using tidyr::separate
I can probably come up with a hacky way to spread
the noise values into columns and set flags. But that works for one attribute at a time, and I have possibly hundreds of these. I do not know all the possible attribute values in advance.
How can I efficiently produce the desired data.frame? Thanks for your time!