Rstudio Jsonlite嵌套列表

问题描述

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")

问题是天气,这是清单吗?并在转换后都保留在一起。

enter image description here

我尝试使用jsonlite展平函数,但没有结果。 问题是,如何将天气分为不同的列(使用+15000个对象)。尝试使用google回答了几个小时,但没有结果对我有用。只是发现这个问题称为嵌套列表,并且某些解决方案似乎使用了dplyr,这使我更加困惑。

这是一行的样子。

list(id = 800. main =“ Clear”。description =“天空晴朗”。图标=“ 01n”)

谢谢。

解决方法

我有一个类似的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)