具有多个对象的嵌套 json 文件中的数据操作

Data manipulation in nested json file with multiple objects

我的 JSON 文件 "json" 的这个子集在 R

library(jsonlite)
json <- '{"year": {"2015":{"id": 10, "number": 1, "amount": 5},"2016": {"id": 2, "number": 6, "amount": 9}}}'
data1 <- jsonlite::fromJSON(json)
v<-as.data.frame(data1)
v

看起来像这样

  year.2015.id year.2015.number year.2015.amount year.2016.id year.2016.number year.2016.amount
1           10                1                5            2                6                9

但我只想要最后一个具有变量 "id"、"number"、"amount" 的对象。 所以想要的输出是这样的。

id  number amount
10  1    5
2   6    9

当嵌套 json 文件并且我只想查看级别时如何实现此目的,其中数据具有变量 id 年份和编号,而不是在具有年份的级别。

此致, 克里斯蒂安·斯科约特

当你自动将dataframe列表列表转换为dataframe时出现问题,你需要访问dataframe列表data1$year而不是data1,然后绑定数据。

正在准备数据

library(jsonlite)

json <- 
  '{"year": {"2015":{"id": 10, "number": 1, "amount": 5},"2016": {"id": 2, "number": 6, "amount": 9}}}'

data1 <- jsonlite::fromJSON(json)

绑定方式一

do.call("rbind", data1$year)
# id number amount
# 2015 10 1      5     
# 2016 2  6      9   

使用dplyr绑定方式二

dplyr::bind_rows(data1$year, .id = NULL)
# # A tibble: 2 x 3
# id number amount
# <int>  <int>  <int>
# 10      1      5
# 2      6      9

使用plyr的绑定方法3

plyr::ldply(data1$year, data.frame, .id = NULL)
# # A tibble: 2 x 3
# id number amount
# <int>  <int>  <int>
# 10      1      5
# 2      6      9

您可以使用 library(jqr) 对 json 本身进行子集化,然后在提取您想要的值后构建 data.frame

jqr::jq( json, '.[][]') %>%
  jqr::combine() %>%
  jsonlite::fromJSON()

#   id number amount
# 1 10      1      5
# 2  2      6      9