0

我正在读取 json 格式的数据源,但无法将其解析为我想要的数据帧。

jsontxt <- '{"sitesEnergy":{"timeUnit":"DAY","unit":"Wh","count":2,"siteEnergyList":[{"siteId":159864,"energyValues":{"measuredBy":"METER","values":[{"date":"2015-09-01 00:00:00","value":2.0},{"date":"2015-09-02 00:00:00","value":2.0}]}},{"siteId":177606,"energyValues":{"measuredBy":"INVERTER","values":[{"date":"2015-09-01 00:00:00","value":null},{"date":"2015-09-02 00:00:00","value":0.0}]}}]}}'
fromJSON(jsontxt,flatten=TRUE)

产量:

$sitesEnergy
$sitesEnergy$timeUnit
[1] "DAY"

$sitesEnergy$unit
[1] "Wh"

$sitesEnergy$count
[1] 2

$sitesEnergy$siteEnergyList
  siteId energyValues.measuredBy                             energyValues.values
1 159864                   METER  2015-09-01 00:00:00, 2015-09-02 00:00:00, 2, 2
2 177606                INVERTER 2015-09-01 00:00:00, 2015-09-02 00:00:00, NA, 0

输出文本的前七行看起来不错,但 energyValues.values 的值是日期和值的串联版本。我期待这样的事情:

  siteId energyValues.measuredBy    energyValues.values.date   energyValues.values.value
1 159864                   METER  2015-09-01 00:00:00                2
2 159864                   METER  2015-09-02 00:00:00                2
3 177606                INVERTER  2015-09-01 00:00:00                NA
2 177606                INVERTER  2015-09-02 00:00:00                0

所以 myJSON 数据包格式不正确,我使用 fromJSON 是否不正确,我需要预处理 jsontxt,还是完全是其他东西?

我试过了:

fromJSON(jsontxt,simplifyVector = FALSE)

但它返回一个列表而不是我需要的数据框。我也尝试过不使用 flatten=TRUE 参数,这不会影响输出。

4

1 回答 1

1

不确定这是不是你想要的...

    library(jsonlite)

    jsontxt <- '{"sitesEnergy":{"timeUnit":"DAY","unit":"Wh","count":2,"siteEnergyList":[{"siteId":159864,"energyValues":{"measuredBy":"METER","values":[{"date":"2015-09-01 00:00:00","value":2.0},{"date":"2015-09-02 00:00:00","value":2.0}]}},{"siteId":177606,"energyValues":{"measuredBy":"INVERTER","values":[{"date":"2015-09-01 00:00:00","value":null},{"date":"2015-09-02 00:00:00","value":0.0}]}}]}}'
    jsontxt<-fromJSON(jsontxt,flatten=TRUE)

    str(jsontxt[[1]][4])

    mydf<- jsontxt[[1]][4][[1]]

    library(tidyr)

    unnest(mydf, energyValues.values)
于 2015-11-05T15:35:26.733 回答