簡體   English   中英

JSON 文件到 R dataframe

[英]JSON file to R dataframe

我有一個 JSON 文件。 雖然原始文件很大,但出於這個問題的目的,我將其簡化為一個更小的可重現示例(無論大小如何,我仍然會遇到相同的錯誤):

{
  "relationships_followers": [
    {
      "title": "",
      "media_list_data": [
        
      ],
      "string_list_data": [
        {
          "href": "https://www.instagram.com/testaccount1",
          "value": "testaccount1",
          "timestamp": 1669418204
        }
      ]
    },
    {
      "title": "",
      "media_list_data": [
        
      ],
      "string_list_data": [
        {
          "href": "https://www.instagram.com/testaccount2",
          "value": "testaccount2",
          "timestamp": 1660426426
        }
      ]
    },
    {
      "title": "",
      "media_list_data": [
        
      ],
      "string_list_data": [
        {
          "href": "https://www.instagram.com/testaccount3",
          "value": "testaccount3",
          "timestamp": 1648230499
        }
      ]
    },
       {
      "title": "",
      "media_list_data": [
        
      ],
      "string_list_data": [
        {
          "href": "https://www.instagram.com/testaccount4",
          "value": "testaccount4",
          "timestamp": 1379513403
        }
      ]
    }
  ]
}

我試圖將其轉換為 R 中的 dataframe,其中包含hrefvaluetimestamp變量的值:

在此處輸入圖像描述

但是當我運行以下命令時,我從另一個關於將 JSON 轉換為 R 的 SO 答案中提取:

library("rjson")

result <- fromJSON(file = "test_file.json")

json_data_frame <- as.data.frame(result)

我遇到了關於不同行的錯誤。

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
  arguments imply differing number of rows: 1, 0

我如何才能將我擁有的內容轉換為所需的 DF 格式?

看起來數據是嵌套的......

試試這個:

library("rjson")
library("dplyr")

result <- fromJSON(file = "test_file.json")
result_list <-sapply(result$relationships_followers,
                     "[[", "string_list_data")
json_data_frame <- bind_rows(result_list)

那是因為有嵌套數據。

df<- as.data.frame(do.call(rbind, lapply(
  lapply(result$relationships_followers, "[[", "string_list_data"), "[[", 1)))

df
#>      href                                     value          timestamp 
#>  "https://www.instagram.com/testaccount1" "testaccount1" 1669418204
#>  "https://www.instagram.com/testaccount2" "testaccount2" 1660426426
#>  "https://www.instagram.com/testaccount3" "testaccount3" 1648230499
#>  "https://www.instagram.com/testaccount4" "testaccount4" 1379513403

注意: jsonlite package 默認情況下在解析 data.frame 方面做得更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM