如何将JSON文件中的指定数据转换为R语言DataFrame?
解决JSON转R DataFrame的报错问题
错误原因
直接对加载后的完整JSON对象执行as.data.frame()会触发报错,因为JSON结构里的header是单条数据(1行),而response$result是多条样本组成的数组(N行),两者行数不匹配,导致R抛出"arguments imply differing number of rows"的错误。
正确处理方案
方法1:用rjson包处理
加载JSON并定位目标数据集
跳过无关的header,直接提取response下的result数组——这才是你需要的多条样本数据:library(rjson) # 加载JSON文件 data <- fromJSON(file = "data.json") # 提取result数组 result_data <- data$response$result提取指定字段并转换为DataFrame
遍历result数组,提取你需要的字段,注意嵌套的attributes可以转成字符串保存,避免结构冲突:# 提取目标字段,处理嵌套的attributes extracted_list <- lapply(result_data, function(item) { list( alias = item$alias, egaStableId = item$egaStableId, centerName = item$centerName, creationTime = item$creationTime, title = item$title, bioSampleId = item$bioSampleId, subjectId = item$subjectId, gender = item$gender, phenotype = item$phenotype, attributes = toJSON(item$attributes) ) }) # 转换为DataFrame final_df <- do.call(rbind, lapply(extracted_list, as.data.frame, stringsAsFactors = FALSE))
方法2:用jsonlite包简化嵌套结构处理
如果attributes是键值对结构,想要直接展开为单独列,用jsonlite包更高效:
library(jsonlite) # 加载JSON并自动解析嵌套结构 data <- fromJSON("data.json") # 提取指定字段并转成DataFrame,自动展开attributes final_df <- as.data.frame( data$response$result[, c("alias", "egaStableId", "centerName", "creationTime", "title", "bioSampleId", "subjectId", "gender", "phenotype", "attributes")] )
关键注意点
- 必须先定位到
result数组层级再做转换,不要直接处理完整的JSON对象。 - 嵌套字段(如
attributes)要根据需求选择转字符串或展开,避免因结构不一致导致转换失败。
内容的提问来源于stack exchange,提问作者beginner
相关产品推荐
相关产品推荐

