簡體   English   中英

如何在R中搜索JSON?

[英]How to search JSON in R?

所以我基本上有一個帶有以下組織的JSON數據結構:

{
  object1: {
    "sub_object1": {
      "attribute1": ["potato", "asparagus", "celery"],
      "attribute2": ["ostrich", "pelican"]
    },
    "sub_object2": {
    }
  },
  object2: {
  }
}

因此,我正在閱讀使用rjson並嘗試搜索結構的內容。 到目前為止,我有這樣的事情:

for (entry in json_obj) {
  if (grepl(query, entry$sub_object1$attribute1, fixed=TRUE)) {
    ... Record result object here ...
  } else if (grepl(query, entry$sub_object1$attribut2, fixed=TRUE)) {
    ... Record result object here ...
  }
}

基本上,如果我搜索“土豆”,我希望它返回如下內容:

{
  object1: {
    "matched_string": "potato",
    "matched_property": attribute1,
    "full_entry": entry
  }
}

Python是我的母語(我將R用作R Shiny前端),所以我從沒想到JSON操作會如此困難! 任何幫助將非常非常感謝!

讀入R中的json文件會將其變成列表列表(列表...)。 然后,您可以遍歷該嵌套列表以返回返回值的類似結構。

例如:

# it's recommended to use jsonlite as the json parser
json <- jsonlite::fromJSON('{
  "object1": {
    "sub_object1": {
      "attribute1": ["potato", "asparagus", "celery"],
      "attribute2": ["ostrich", "pelican"]
    },
    "sub_object2": {
    }
  },
  "object2": {
  }
}')

find <- function(obj, string)
{
    lapply(obj, function(x) {
        if(is.list(x))
            find(x, string)
        else grepl(string, x, fixed=TRUE)
    })
}

jsonlite::toJSON(find(json, "potato"), auto_unbox=TRUE, pretty=TRUE)
#{
#  "object1": {
#    "sub_object1": {
#      "attribute1": [true, false, false],
#      "attribute2": [false, false]
#    },
#    "sub_object2": {}
#  },
#  "object2": {}
#} 

我假設一旦有了上面的json,就可以使用自己喜歡的語言將其轉換為所需的格式(問題中並未詳細介紹)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM