我有一个JSON输入,我从服务器获取,我想将其解析为数据框对象。
结构:
紧凑表格
'{"total_rows":2,"offset":0,"rows":[{"id":"1","key":["1001"],"value":{"context":"1001","application_id":"1","cust_assets_total":1550000}},{"id":"2","key":["1001"],"value":{"context":"1001","application_id":"2","cust_assets_total":1550000}}]}'
漂亮的表格
{
"total_rows": 2,
"offset": 0,
"rows": [
{
"id": "1",
"key": [
"1001"
],
"value": {
"context": "1001",
"application_id": "1",
"cust_assets_total": 1550000
}
},
{
"id": "2",
"key": [
"1001"
],
"value": {
"context": "1001",
"application_id": "2",
"cust_assets_total": 1550000
}
}
]
}
预期输出:
context application_id cust_assets_total
1001 1 1550000
1001 2 1550000
使用的代码:
library(jsonlite)
raw_data <- '{"total_rows":2,"offset":0,"rows":[{"id":"1","key":["1001"],"value":{"context":"1001","application_id":"1","cust_assets_total":1550000}},{"id":"2","key":["1001"],"value":{"context":"1001","application_id":"2","cust_assets_total":1550000}}]}'
temp <-fromJSON(paste(readLines(raw_data),collapse=""))
但这导致了错误:
Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
cannot open file '{"total_rows":2,"offset":0,"rows":[{"id":"1","key":["1001"],"value":{"context":"1001","application_id":"1","cust_assets_total":1550000}},{"id":"2","key":["1001"],"value":{"context":"1001","application_id":"2","cust_assets_total":1550000}}]}': No such file or directory
答案 0 :(得分:1)
如果你将textConnection
包裹在“raw_data”周围,你可以阅读里程但是更容易将其删除:
> temp <-fromJSON(raw_data)
> temp
$total_rows
[1] 2
$offset
[1] 0
$rows
id key value.context value.application_id value.cust_assets_total
1 1 1001 1001 1 1550000
2 2 1001 1001 2 1550000
注意:...此版本的fromJSON
为您提供了一个三元素命名列表。