是否有 XQuery/XPath 的 JSON 等价物?

新手上路,请多包涵

在复杂的 JSON 数组和散列中搜索项目时,例如:

 [
    { "id": 1, "name": "One", "objects": [
        { "id": 1, "name": "Response 1", "objects": [
            // etc.
        }]
    }
]

我可以使用某种查询语言来查找项目 in [0].objects where id = 3 吗?

原文由 Naftuli Kay 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 423
2 个回答

JMESPath 是一个相当成熟的库,具有详细的规范和对多种语言的支持。

语法示例:
 // Select a single item
people[1].firstName

// Select a slice of an array
people[0:5]

// Select all the first names
people[*].firstName

// Select all first names based on search term
people[?state=='VA'].firstName

// Count how many people are over 35
length(people[?age>`35`])

// Select only the name and age of people over 35
people[?age>`35`].{name: name, age: age}

// Join expressions together to sort and join elements into a string
people[?state == 'WA'].name | sort(@) | join(', ', @)

您可以在 文档 中使用更多的实例。

JS 库缩小到 19kb,因此可能比某些库大,但考虑到广泛的功能,您可能会发现它是值得的。

其他选项

还有一些用于遍历/过滤 JSON 数据的其他选项,以及一些语法示例来帮助您比较…

.automobiles{.maker === "Honda" && .year > 2009}.model

.automobiles .maker:val("Honda") .model

$.automobiles[?(@.maker='Honda')].model

原文由 Simon East 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏