【问题标题】:Turn a json list to a data frame将 json 列表转换为数据框
【发布时间】:2020-05-15 09:05:52
【问题描述】:

我有一个保存为文本的 json 列表,我正在尝试将其转换为数据框。列表看起来像这样:

`{"posts": {
        "data": [
          {
            "comments": {
              "data": [
                {
                  "created_time": "2020-01-25T16:48:03+0000",
                  "message": "I love all kind of art and paintings. However 19 thousand dollars for a painting is entirely too much!!. ",
                  "id": "1579832716452874_1373756966159579"
                },
                {
                  "created_time": "2020-01-25T15:21:29+0000",
                  "message": "The wind blows a piece of paper and lands next to your house. You unravel it, \"Hey hope you are having a nice day!\"...",
                  "id": "1579832716452874_1373704542831488"
                }
              ]
            }
          }
        ]
      }
    }`

等等。我希望将我的数据框拆分为以下列:

`created_time|message|id`

连同他们各自的数据。 我尝试了以下命令,但没有成功,因为我得到了完全相同的输出:

` df <- data.frame(matrix(unlist(data), ncol=length(data), byrow = FALSE))`

另外由于数据保存为文本,json 包(rjson,jsonlite)将不起作用。 任何建议将不胜感激。

【问题讨论】:

  • “另存为文本”是什么意思?这听起来是件好事。我不确定 JSON 存储为文本以外的其他内容会是什么样子。
  • 检查this线程。
  • 所以使用数据
  • 您能否完成您的示例数据,使其在语法上是有效的 JSON 以进行测试?现在它被截断了,所以不清楚原始结构是什么。
  • @Brian 已更新完整数据

标签: r json list dataframe


【解决方案1】:

您似乎遇到的问题与引号有关。如果您将 JSON 对象保存为文本文件,{jsonlite} 将在读取文件时自动转义这些字符。 fromJSON 的默认值尽可能将列表展平为数据框,这正是您想要的。

x <- jsonlite::fromJSON("complex_json.json")

x_df <- x$posts$data[1]$comments$data[[1]]

tibble::as_tibble(x_df)  # tibble is for pretty-printing purposes only
# A tibble: 2 x 3
  created_time        message                                                          id                   
  <chr>               <chr>                                                            <chr>                
1 2020-01-25T16:48:0~ "I love all kind of art and paintings. However 19 thousand doll~ 1579832716452874_137~
2 2020-01-25T15:21:2~ "The wind blows a piece of paper and lands next to your house. ~ 1579832716452874_137~

唯一棘手的一点是找出x$posts$data[1]$comments$data[[1]]。我总是在控制台以交互方式执行此操作,偶尔检查结果对象的str(),以查看哪些隐藏的嵌套级别没有打印清楚。

【讨论】:

    猜你喜欢
    • 2019-02-08
    • 2023-02-23
    • 2020-09-02
    • 2021-02-09
    • 2018-08-25
    • 2021-09-27
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    相关资源
    最近更新 更多