I want to read some json data into a dataframe. I know that is not always possible, but my json is appears to be quite well structured and consistent.
dput(test)
list(`0` = list(Code = "A", Name = "Agilent Technologies Inc",
StartDate = "2000-06-05", EndDate = NULL, IsActiveNow = 1,
IsDelisted = 0), `1` = list(Code = "AAL", Name = "American Airlines Group",
StartDate = "2015-03-23", EndDate = "2024-09-23", IsActiveNow = 0,
IsDelisted = 0), `2` = list(Code = "AAP", Name = "Advance Auto Parts Inc",
StartDate = "2015-07-09", EndDate = "2023-08-25", IsActiveNow = 0,
IsDelisted = 0), `3` = list(Code = "AAPL", Name = "Apple Inc",
StartDate = "1982-11-30", EndDate = NULL, IsActiveNow = 1,
IsDelisted = 0), `4` = list(Code = "ABBV", Name = "AbbVie Inc",
StartDate = "2013-01-02", EndDate = NULL, IsActiveNow = 1,
IsDelisted = 0))
I was able to get this into a dataframe of sorts by using:
df <- data.frame(Reduce(rbind, test))
However, this just creates a dataframe with a bunch of lists inside:
str(df)
> str(df)
'data.frame': 5 obs. of 6 variables:
$ Code :List of 5
..$ init: chr "A"
..$ : chr "AAL"
..$ : chr "AAP"
..$ : chr "AAPL"
..$ : chr "ABBV"
$ Name :List of 5
..$ init: chr "Agilent Technologies Inc"
..$ : chr "American Airlines Group"
..$ : chr "Advance Auto Parts Inc"
..$ : chr "Apple Inc"
..$ : chr "AbbVie Inc"
$ StartDate :List of 5
..$ init: chr "2000-06-05"
..$ : chr "2015-03-23"
..$ : chr "2015-07-09"
..$ : chr "1982-11-30"
..$ : chr "2013-01-02"
$ EndDate :List of 5
..$ init: NULL
..$ : chr "2024-09-23"
..$ : chr "2023-08-25"
..$ : NULL
..$ : NULL
$ IsActiveNow:List of 5
..$ init: num 1
..$ : num 0
..$ : num 0
..$ : num 1
..$ : num 1
$ IsDelisted :List of 5
..$ init: num 0
..$ : num 0
..$ : num 0
..$ : num 0
..$ : num 0
I can’t find a way to unlist the lists into a traditional dataframe.
I have looked at the similar questions on SO but I can’t make them work or understand what the functions are doing.
jsonlite::fromJSON()would do what you want directly? E.g., if the original data looked something likejsonlite::toJSON(unname(test))then read it asjsonlite::fromJSON().