如何读取嵌套的JSON结构?

问题描述 投票:3回答:2

我有一些JSON,看起来像这样。

"total_rows":141,"offset":0,"rows":[
{"id":"1","key":"a","value":{"SP$Sale_Price":"240000","CONTRACTDATE$Contract_Date":"2006-10-26T05:00:00"}},
{"id":"2","key":"b","value":{"SP$Sale_Price":"2000000","CONTRACTDATE$Contract_Date":"2006-08-22T05:00:00"}},
{"id":"3","key":"c","value":{"SP$Sale_Price":"780000","CONTRACTDATE$Contract_Date":"2007-01-18T06:00:00"}},
...

在R中,什么是最简单的方法来产生一个散点图?SP$Sale_Price 与...相比 CONTRACTDATE$Contract_Date?

我已经走到这一步了

install.packages("rjson")
library("rjson")
json_file <- "http://localhost:5984/testdb/_design/sold/_view/sold?limit=100"
json_data <- fromJSON(file=json_file)
install.packages("plyr")
library(plyr)
asFrame <- do.call("rbind.fill", lapply(json_data, as.data.frame))

但现在我卡住了...

> plot(CONTRACTDATE$Contract_Date, SP$Sale_Price)
Error in plot(CONTRACTDATE$Contract_Date, SP$Sale_Price) : 
  object 'CONTRACTDATE' not found

如何使这个工作?

json r plyr rbind
2个回答
4
投票

假设你有以下JSON文件。

txt <- '{"total_rows":141,"offset":0,"rows":[
  {"id":"1","key":"a","value":{"SP$Sale_Price":"240000","CONTRACTDATE$Contract_Date":"2006-10-26T05:00:00"}},
  {"id":"2","key":"b","value":{"SP$Sale_Price":"2000000","CONTRACTDATE$Contract_Date":"2006-08-22T05:00:00"}},
  {"id":"3","key":"c","value":{"SP$Sale_Price":"780000","CONTRACTDATE$Contract_Date":"2007-01-18T06:00:00"}}]}'

那么你可以用以下方法读取它 jsonlite 包。

library(jsonlite)
json_data <- fromJSON(txt, flatten = TRUE)

# get the needed dataframe
dat <- json_data$rows
# set convenient names for the columns
# this step is optional, it just gives you nicer columnnames
names(dat) <- c("id","key","sale_price","contract_date")
# convert the 'contract_date' column to a datetime format
dat$contract_date <- strptime(dat$contract_date, format="%Y-%m-%dT%H:%M:%S", tz="GMT")

现在你可以策划。

plot(dat$contract_date, dat$sale_price)

这就意味着:

enter image description here


如果你不选择扁平化JSON,你可以这样做:

json_data <- fromJSON(txt)

dat <- json_data$rows$value

sp <- strtoi(dat$`SP$Sale_Price`)
cd <- strptime(dat$`CONTRACTDATE$Contract_Date`, format="%Y-%m-%dT%H:%M:%S", tz="GMT")
plot(cd,sp)

也会得到同样的结果

enter image description here


0
投票

我找到了一个不丢弃字段名的方法。

install.packages("jsonlite")
install.packages("curl")
json <- fromJSON(json_file)
r <- json$rows

在这一点上 r 看起来是这样的。

> class(r)
[1] "data.frame"
> colnames(r)
[1] "id"    "key"   "value"

在经过了更多的谷歌搜索和尝试错误之后 我找到了这个。

f <- r$value
sp <- strtoi(f[["SP$Sale_Price"]])
cd <- strptime(f[["CONTRACTDATE$Contract_Date"]], format="%Y-%m-%dT%H:%M:%S", tz="GMT")
plot(cd,sp)

我的全部数据集的结果是... And the result on my full data -set...

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.