gpt4 book ai didi

json - 如何读取嵌套的 JSON 结构?

转载 作者:行者123 更新时间:2023-12-04 02:16:03 26 4
gpt4 key购买 nike

我有一些像这样的 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_PriceCONTRACTDATE$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 文件:

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

关于json - 如何读取嵌套的 JSON 结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33578930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com