在R中,如何将参数与JSON数据中的值集链接起来?

时间:2014-10-28 16:44:07

标签: json r

以下JSON数据

       "parameters": [
            {
                "parameterName": "IntervalToIgnoreDuringTransitions",
                "values": [
                    {
                        "createdByTimestamp": "2014-09-22T14:39:25.717Z",
                        "createdByUser": "tis",
                        "modifiedByUser": "",
                        "analyticParameterValueId": 502,
                        "analyticParameterNameId": 502,
                        "analyticParameterValue": "0"
                    }
                ]
            },
            {
                "parameterName": "DateRange",
                "values": [
                    {
                        "createdByTimestamp": "2014-09-22T14:38:25.297Z",
                        "createdByUser": "tis",
                        "modifiedByUser": "",
                        "analyticParameterValueId": 501,
                        "analyticParameterNameId": 501,
                        "analyticParameterValue": "12"
                    }
                ]
            }
        ]

在R

中创建以下data.frame结构
'data.frame':   2 obs. of  2 variables:
 $ parameterName: chr  "IntervalToIgnoreDuringTransitions" "DateRange"
 $ values       :List of 2
  ..$ :'data.frame':    1 obs. of  6 variables:
  .. ..$ createdByTimestamp      : chr "2014-09-22T14:39:25.717Z"
  .. ..$ createdByUser           : chr "tis"
  .. ..$ modifiedByUser          : chr ""
  .. ..$ analyticParameterValueId: int 502
  .. ..$ analyticParameterNameId : int 502
  .. ..$ analyticParameterValue  : chr "0"
  ..$ :'data.frame':    1 obs. of  6 variables:
  .. ..$ createdByTimestamp      : chr "2014-09-22T14:38:25.297Z"
  .. ..$ createdByUser           : chr "tis"
  .. ..$ modifiedByUser          : chr ""
  .. ..$ analyticParameterValueId: int 501
  .. ..$ analyticParameterNameId : int 501
  .. ..$ analyticParameterValue  : chr "12"

是否有将参数名称与各自值相关联的简单方法?

例如,如果data.frame被称为df,我想使用df $ DateRange $ analyticParameterValue来返回" 12"。

1 个答案:

答案 0 :(得分:2)

这应该这样做:

library(jsonlite)

tmp <- fromJSON('{"parameters": [
{
  "parameterName": "IntervalToIgnoreDuringTransitions",
  "values": [
{
  "createdByTimestamp": "2014-09-22T14:39:25.717Z",
  "createdByUser": "tis",
  "modifiedByUser": "",
  "analyticParameterValueId": 502,
  "analyticParameterNameId": 502,
  "analyticParameterValue": "0"
}
]
},
{
  "parameterName": "DateRange",
  "values": [
{
  "createdByTimestamp": "2014-09-22T14:38:25.297Z",
  "createdByUser": "tis",
  "modifiedByUser": "",
  "analyticParameterValueId": 501,
  "analyticParameterNameId": 501,
  "analyticParameterValue": "12"
}
]
}
]}')

dat <- tmp$parameters$values
names(dat) <- tmp$parameters$parameterName

dat$DateRange$analyticParameterValue
## [1] "12"