我有一个从查询返回到 Google Books API 的 JSON 文档,例如:
{ "items": [ { "volumeInfo": { "industryIdentifiers": [ { "type": "OTHER", "identifier": "OCLC:841804665" } ] } }, { "volumeInfo": { "industryIdentifiers": [ { "type": "ISBN_10", "identifier": "156898118X"...
我需要 ISBN 编号(类型:ISBN_10 或 ISBN_13)并且我编写了一个简单的循环来遍历已解析的 JSON (parsed = json.parse(my_uri_response)
)。在此循环中,我有一个 next if k['type'] = "OTHER"
将“type”设置为“OTHER”。
如何才能最好地从我的 JSON 示例中提取一个 ISBN 编号?不是全部,只有一个。
像 XPath 搜索这样的东西会有帮助。
最佳答案
JSONPath可能正是您正在寻找的:
require 'jsonpath'
json = #your raw JSON above
path = JsonPath.new('$..industryIdentifiers[?(@.type == "ISBN_10")].identifier')
puts path.on(json)
结果:
156898118X
参见 this page了解 XPath 如何转换为 JSONPath。它帮助我确定了上面的 JSONPath。
关于ruby - 在 Ruby 中解析 JSON(如 XPATH),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23352180/