ruby - 在 Ruby 中解析 JSON(如 XPATH)

标签 ruby json

我有一个从查询返回到 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/

相关文章:

javascript - 有什么办法可以绕过测试服务器的跨源资源共享?

python - SQLALchemy:查询 Postgres JSONB 列的单个键或键的子集

ruby - 我如何使用 ruby​​ 生成数字组合?

css - rails 上的样式下拉 ruby

ruby - 如何创建一个存储实例的类?

javascript - ReactJS,尝试从 JIRA 的 REST API 获取 JSON 数据,但无法这样做。

jQuery .ajax() 调用失败

xml - JSON 是一种语言吗?如果不是,它会如何分类?

ruby-on-rails - 如何在 Rails 3.2 中使用 JBuilder 渲染 json

ruby - 为什么单引号字符串内需要双反斜杠转义?