【问题标题】:R: How to convert a nested JSON to dataframe [duplicate]R:如何将嵌套的 JSON 转换为数据框 [重复]
【发布时间】:2020-03-05 02:20:21
【问题描述】:

我有嵌套的 JSON(行)文件,看起来像

[{"ok":2, "nested": {"meh":2, "hehe":{"a":1, "b":2 }}},
{"ok":3, "nested": {"meh":10, "hehe":{"a":1, "b":2}}},
{"ok":4, "nested": {"meh":11, "hehe":{"a":1, "b":2}}}]
...

我希望将其取消嵌套到 data.frame 表示的 CSV 表单中

ok, nested.meh, nested.hehe.a, nested.hehe.b
2, 2, 1, 2
3, 10, 1, 2
4, 11, 1, 2
...

我试过了

a = jsonlite::read_json("file.json")

然后是列表列表,似乎需要自定义编码才能取消嵌套,但我想读取一般嵌套文件。有包来处理这个吗?我查看了rlist 的文档,但找不到信息,因为rlist::table 不起作用。

【问题讨论】:

标签: r json


【解决方案1】:

这对我有用:

a = jsonlite::fromJSON("file.json", flatten = TRUE)

我通过将以下内容粘贴到空白 Notepad++ 文本文档中创建了 file.json。有时我将json 文件导入R 的问题是由于文本格式问题,所以还要仔细检查原始文件是否有错误的空格或其他字符。

数据

[{"ok":2, "nested": {"meh":2, "hehe":{"a":1, "b":2 }}},
{"ok":3, "nested": {"meh":10, "hehe":{"a":1, "b":2}}},
{"ok":4, "nested": {"meh":11, "hehe":{"a":1, "b":2}}}]

【讨论】:

  • 你给str(a)打过电话吗?我得到的 看起来 像一个平面数据框,但一点调查表明它实际上是 OP 描述的嵌套列表的类型
  • 糟糕,忘记添加flatten = TRUE,正在编辑中
【解决方案2】:

我通常会选择 flatten_json 包

import flatten_json

ex_json = [{"ok":2, "nested": {"meh":2, "hehe":{"a":1, "b":2 }}},
{"ok":3, "nested": {"meh":10, "hehe":{"a":1, "b":2}}},
{"ok":4, "nested": {"meh":11, "hehe":{"a":1, "b":2}}}]

ex_df = pd.io.json.json_normalize(flatten_json.flatten_json(ex_json[0], separator="."))

【讨论】:

  • 那是 Python;这个问题是关于 R
  • 天哪,你是对的,哎呀!
猜你喜欢
  • 1970-01-01
  • 2017-04-12
  • 2023-03-20
  • 1970-01-01
  • 2023-01-12
  • 2019-07-08
  • 2020-11-12
相关资源
最近更新 更多