2

I'm trying to parse some results from an API. The API returns a JSON result for a given value. The API can only handle one value at a time so I lapply to get all the results. <- If this is a bad start point happy to here a better way!

Each JSON response has some nested info. I'm trying to get the data into one single data.frame with the nested structure resolved.

I've been playing around with jsonlite and purrr for much of the afternoon trying to get this working and ideally resilient.

How does one successfully convert a nested json structure into a data.frame for multiple json documents/records using R?

MRE

library(jsonlite)
a <- LETTERS[1:5]
b <- letters[1:5]
c <- rep(data.frame(d=LETTERS[1:5]),5)

strSetup <- list(a, b, c)
dfSetup  <- data.frame(a, b, c)

jsonStr <- toJSON(rep(strSetup,3))

finalStr <- rbind(dfSetup,dfSetup,dfSetup)

I'm trying to go from jsonStr to finalStr.

Jaap
  • 81,064
  • 34
  • 182
  • 193
Steph Locke
  • 5,951
  • 4
  • 39
  • 77

1 Answers1

0

If I understand correctly, you are storing all the JSON strings returned by the API into a character vector. That means that line 9 of your example is a little off and this should work.

library(jsonlite)
a <- LETTERS[1:5]
b <- letters[1:5]
c <- rep(data.frame(d=LETTERS[1:5]),5)

strSetup <- list(a, b, c)
dfSetup  <- data.frame(a, b, c)

jsonStr <- rep(toJSON(strSetup),3)

finalStr <- rbind(dfSetup,dfSetup,dfSetup)

finalStr2 <- do.call(
  what = rbind,
  args = lapply(
    X = jsonStr,
    FUN = function(x){
      data.frame(fromJSON(x))
      }
    )
  )

print(all(finalStr == finalStr2))

The caveat there is that names(finalStr) != names(finalStr2). However, I don't think that's avoidable, since you indicated that the JSON string you're receiving from the API does not contain names.

If I misunderstood, please let me know.

Adam Hoelscher
  • 1,804
  • 2
  • 17
  • 33
  • It's coming in as a list due to the lapply - each individual call returns a json object and I was looping through the input items to get the responses. I'm giving your code a whirl now though - I should be able to loop to a vector and if that makes life easier I'm all for it. – Steph Locke Feb 16 '16 at 20:13
  • Ok. So you're using `lapply` with `FUN` equal to the function that pulls the JSON from the API? Can you wrap `unlist` around the `lapply` to convert it back to a vector? – Adam Hoelscher Feb 16 '16 at 20:59