【问题标题】:How do I generate multilevel JSON with R?如何使用 R 生成多级 JSON?
【发布时间】:2016-04-20 02:24:27
【问题描述】:

我想使用从 R 输出的 JSON 文件创建一个treemap(或 Python,如果我真的不能在 R 中执行此操作,我可以切换到 Python 吗?)。这 数据看起来像 this:

cat type    pop
Buddhism    Other   116237936
Christianity    Anglican    36955033
Christianity    Catholic    391332035
Christianity    Orthodox    98501171
Christianity    Other   13674466
Christianity    Mahayana    160887585
Islam   Ibadhi  62273219
Islam   Shia    19436742
Islam   Sunni   49050320
Judaism Conservative    1426350
Judaism Orthodox    856827
Judaism Other   7796835
Judaism Reform  1929388

我需要 json 看起来像 ...

  {"name": "Buddhism",
   "children": 
        {"name": "Other", "size": 116237936}
    },
    {
     "name": "Christianity",
     "children": [
      {"name": "Anglican", "size": 36955033},
      {"name": "Catholic", "size": 391332035},
      {"name": "Orthodox", "size": 98501171},
      {"name": "Other", "size": 13674466},
      {"name": "Mahayana", "size": 160887585}
     ]
    } ...

我查看了rjsonjsonlite 的文档,但似乎都没有让它看起来很简单。

【问题讨论】:

标签: python json r


【解决方案1】:

也许这样的事情可以完成这项工作? Split cat 列上的数据框,然后从每个结果数据框中删除第一列,并使用 jsonlite 包中的 toJSON 转换为 JSON。

JSONoutput <- jsonlite::toJSON(lapply(split(data, data$cat), function(x) {x[,-1]}))

【讨论】:

  • 这已经非常接近了,虽然我现在有 {"Buddhism":[{"type":"Other","pop":116237936}] 并且我需要将它强制转换为 {"name": "Buddhism", "children":[{...}] 一些可以工作的东西。
  • 我认为JSONoutput &lt;- jsonlite::toJSON(lapply(split(data, data$cat), function(x) {list("children"=x[,-1])})) 可能会为你做到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多