简体   繁体   English

使用 R 和 jsonlite 迭代 JSON 元素以修复缺失值

[英]Iterating through JSON elements to fix missing values using R and jsonlite

I'm working with a JSON file and trying to flatten it into a data.frame using the jsonlite package.我正在处理一个 JSON 文件,并尝试使用jsonlite package 将其扁平化为data.frame

The main set of objects in the array don't have a key, and so instead of flattening into rows, it's creating a column for each object (and its key-value pairs).数组中的主要对象集没有键,因此不是展平成行,而是为每个 object(及其键值对)创建一列。

How can I iterate through the JSON object to add a key to each object value so that I can view this data as a readable data.frame ?我如何遍历 JSON object 以向每个 object 值添加一个键,以便我可以将此数据视为可读的data.frame

This is the code I'm using:这是我正在使用的代码:

jsonfile <- jsonlite::fromJSON("filename"), simplifyDataFrame=TRUE)

And so this:所以这个:

{
  "SUCCESS ACADEMY": {
    "districtName": "SUCCESS SD",
    "isPublic": true
  },
  "FAILURE ACADEMY": {
    "districtName": "FAIL SD",
    "isPublic": true
  }
}

Turns into this:变成这样:


+------------------------------+--------------------------+------------------------------+--------------------------+
| SUCCESS ACADEMY.districtName | SUCCESS ACADEMY.isPublic | Failure Academy.districtName | Failure Academy.isPublic |
+------------------------------+--------------------------+------------------------------+--------------------------+

When I want this instead:当我想要这个时:

+-----------------+--------------+----------+
|   School Name   | districtName | isPublic |
+-----------------+--------------+----------+
| SUCCESS ACADEMY | SUCCESS SD   | true     |
| FAILURE ACADEMY | FAIL SD      | true     |
+-----------------+--------------+----------+

There may be a direct way but treating it as a list of data frames thne binding them together seems adequate:可能有一种直接的方法,但将其视为数据帧列表,将它们绑定在一起似乎就足够了:

library(data.table)
library(magrittr)

jsonlite::fromJSON(txt= '{
  "SUCCESS ACADEMY": {
    "districtName": "SUCCESS SD",
    "isPublic": true
  },
  "FAILURE ACADEMY": {
    "districtName": "FAIL SD",
    "isPublic": true
  }
}') %>% 
  lapply(as.data.table) %>%
  rbindlist(idcol = "School_name")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM