【问题标题】:How can i retrieve the "values" of json with R?如何使用 R 检索 json 的“值”?
【发布时间】:2018-02-28 16:11:28
【问题描述】:

所以我尝试了任何方法来获取特定的键:值。但似乎我找不到解决方案。有什么帮助吗?

{  
   "contracts":[  
      {  
         "contractid":"BemDRHtv17",
         "cid":"",
         "category":"WORK",
         "mainCategory":"Grundeinkommen",
         "configured":false,
         "customMainCategory":null,
         "customSubCategory":null,
         "customContractPartner":null,
         "amount":209200,
         "interval":"MONTHLY",
         "runTime":null,
         "periodOfNotice":null,
         "cancelationAlert":null,
         "extensionPeriod":null,
         "contractPartner":{  
            "creditorId":null,
            "name":null,
            "__typename":"ContractPartner"
         },
         "__typename":"Contract"
      },
P.s 我正在尝试访问 mainCategory 的键和值/搜索其特定值。

【问题讨论】:

  • 你试过jsonliterjson吗?请显示您迄今为止尝试过的任何代码。
  • nvm 修复了它。我刚刚创建了一个包含所需信息的小数据框。像这样:我

标签: json r key-value


【解决方案1】:

您可以使用以下方法访问某些密钥

使用像 rjsonjsonlite 这样的库

使用fromJSON() 函数将 json 数据调用到 R 中。假设您像这样保存数据

library(jsonlite)
jsonData = fromJSON("PATH")  #Link to the file or html link

现在您可以使用这种方法解析您的内容并将结果保存在矩阵(或您想要使用的任何数据类)中

variable <- as.matrix(jsonData$contracts$mainCategory)

【讨论】:

  • 感谢您的回答。我意识到仅使用 $ char 来访问 json 元素是多么容易...
【解决方案2】:

您可以使用library(jqr) 访问原始 JSON 的特定元素,而不是将整个 JSON 转换为 R 对象

library(jqr)

jq(js, ".contracts[].mainCategory")

# "Grundeinkommen"

数据

js <- '{  
   "contracts":[  
{  
"contractid":"BemDRHtv17",
"cid":"",
"category":"WORK",
"mainCategory":"Grundeinkommen",
"configured":false,
"customMainCategory":null,
"customSubCategory":null,
"customContractPartner":null,
"amount":209200,
"interval":"MONTHLY",
"runTime":null,
"periodOfNotice":null,
"cancelationAlert":null,
"extensionPeriod":null,
"contractPartner":{  
"creditorId":null,
"name":null,
"__typename":"ContractPartner"
},
"__typename":"Contract"
}
]}
'

【讨论】:

    猜你喜欢
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 2015-01-13
    • 1970-01-01
    相关资源
    最近更新 更多