首页 > 解决方案 > R:如何将嵌套的 JSON 转换为数据框

问题描述

我有嵌套的 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它不起作用。

标签: rjson

解决方案


我通常会选择 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="."))

推荐阅读