【问题标题】:Rstudio Jsonlite nested ListRstudio Jsonlite 嵌套列表
【发布时间】:2020-10-22 02:10:59
【问题描述】:

一般来说,我对 Rstudio 很陌生,所以我的一些概念不清楚。尝试在 JSON 文件上查看来自 OpenWeatherMap 的数据。它们看起来像这样(缩短数据以在此处查看)。

[{"city_name":"X-Land"  
    "lon": -10.10,  
    "lat": 10.10  
  ,"main":{  
"temp":19,  
"temp_min":18,  
"temp_max":20 }  
  "weather": [{  
      "id": 800,  
      "main": "Clear",  
      "description": "clear sky",  
      "icon": "01d"  
    }],  
  "base": "stations", }]

使用jsonlite几乎所有信息都正确显示

library(jsonlite)  
jsonData = fromJSON ("weatherfile.json")

问题是天气,它是一个列表?并且在转换后它们都保持在一起。

我尝试使用 jsonlite flatten 函数但没有结果。 问题是,我如何将天气分成不同的列(使用 +15000 个对象)。试图用谷歌搜索几个小时的答案,但没有一个结果对我有用。才发现问题叫嵌套列表,有的解决方案貌似是用dplyr,更让我困惑。

这就是一行的样子。

list(id = 800.main = "Clear".description = "天空晴朗".icon = "01n")

谢谢。

【问题讨论】:

    标签: r json jsonlite


    【解决方案1】:

    我有一个类似的 JSON 问题,我正在使用这个解决方案,使用嵌套的 purrr::map() 调用来提取特定的嵌套元素: pull all elements with specific name from a nested list

    提取特定元素的示例(更新 JSON 以使其有效):

    weatherfile.json

    [{"city_name":"X-Land",
      "lon":-10.10,
      "lat":10.10,
      "main":{
        "temp":19,
        "temp_min":18,
        "temp_max":20
      },
      "weather":[{
        "id":800,
        "main":"Clear",
        "description":"clear sky",
        "icon":"01d"
      }],
      "base":"stations"
    }]
    

    example_1.R

    library(jsonlite)
    library(purrr)
    library(dplyr)
    library(tidyr)
    
    jsonData <- jsonlite::fromJSON("weatherfile.json", flatten = TRUE) %>% 
      dplyr::mutate(weather_id = purrr::map(weather, "id"),
             weather_main = purrr::map(weather, "main"),
             weather_desc = purrr::map(weather, "description"),
             weather_icon = purrr::map(weather, "icon"))
    

    如果您希望所有内容都嵌套在 weather 中,请尝试使用 tidyr::unnest_wider()`!

    example_2.R

    jsonData_unnest <- jsonlite::fromJSON("weatherfile.json", flatten = TRUE) %>% 
      tidyr::unnest_wider(weather)
    

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多