Javascript 是否有等效于 XQuery/XPath 的 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8481380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:09:38  来源:igfitidea点击:

Is there a JSON equivalent of XQuery/XPath?

javascriptjsonxpathxquery

提问by Naftuli Kay

When searching for items in complex JSON arrays and hashes, like:

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

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

Is there some kind of query language I can used to find an item in [0].objects where id = 3?

是否有某种查询语言可以用来查找项目in [0].objects where id = 3

采纳答案by Mike Christensen

Yup, it's called JSONPath. The source is now on GitHub.

是的,它叫做JSONPath。源现在在GitHub 上

It's also integrated into DOJO.

它还集成到DOJO 中

回答by Brian Clozel

I think JSONQuery is a superset of JSONPath and thus replaces it in dojo. Then there's also RQL.

我认为 JSONQuery 是 JSONPath 的超集,因此在 dojo 中替换了它。然后还有RQL

From Dojo documentation:

从 Dojo 文档:

JSONQuery is an extended version of JSONPath with additional features for security, ease of use, and a comprehensive set of data querying tools including filtering, recursive search, sorting, mapping, range selection, and flexible expressions with wildcard string comparisons and various operators.

JSONQuery 是 JSONPath 的扩展版本,具有安全性、易用性和一套全面的数据查询工具的附加功能,包括过滤、递归搜索、排序、映射、范围选择以及具有通配符字符串比较和各种运算符的灵活表达式。

JSONselecthas another point of view on the question (CSS selector-like, rather than XPath) and has a JavaScript implementation.

JSONselect对这个问题有另一个观点(类似 CSS 选择器,而不是 XPath)并且有一个JavaScript 实现

回答by grtjn

Other alternatives I am aware of are

我知道的其他选择是

  1. JSONiqspecification, which specifies two subtypes of languages: one that hides XML details and provides JS-like syntax, and one that enriches XQuery syntax with JSON constructors and such. Zorbaimplements JSONiq.
  2. Corona, which builds on top of MarkLogic provides a REST interface for storing, managing, and searching XML, JSON, Text and Binary content.
  3. MarkLogic6 and later provide a similar REST interface as Corona out of the box.
  4. MarkLogic8 and later support JSON natively in both their XQuery and Server-side JavaScript environment. You can apply XPath on it.
  1. JSONiq规范,它指定了两种语言子类型:一种隐藏 XML 细节并提供类似 JS 的语法,另一种使用 JSON 构造函数等丰富 XQuery 语法。Zorba实现了 JSONiq。
  2. Corona构建在 MarkLogic 之上,提供了一个用于存储、管理和搜索 XML、JSON、文本和二进制内容的 REST 接口。
  3. MarkLogic6 及更高版本提供了与 Corona 类似的开箱即用的 REST 接口。
  4. MarkLogic8 及更高版本在其 XQuery 和服务器端 JavaScript 环境中原生支持 JSON。您可以在其上应用 XPath。

HTH.

哈。

回答by Simon East

To summarise some of the current options for traversing/filtering JSON data, and provide some syntax examples...

总结一些当前用于遍历/过滤 JSON 数据的选项,并提供一些语法示例...

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

  • json:select()(inspired more by CSS selectors)
    .automobiles .maker:val("Honda") .model

  • JSONPath(inspired more by XPath)
    $.automobiles[?(@.maker='Honda')].model

  • JS路径
    .automobiles{.maker === "Honda" && .year > 2009}.model

  • json:select()(更多地受到 CSS 选择器的启发)
    .automobiles .maker:val("Honda") .model

  • JSONPath(更多地受到 XPath 的启发)
    $.automobiles[?(@.maker='Honda')].model

I think JSPath looks the nicest, so I'm going to try and integrate it with my AngularJS + CakePHP app.

我认为 JSPath 看起来最好,所以我将尝试将它与我的 AngularJS + CakePHP 应用程序集成。

(I originally posted this answer in another threadbut thought it would be useful here, also.)

(我最初在另一个帖子中发布了这个答案,但认为它在这里也很有用。)

回答by dfilatov

Try to using JSPath

尝试使用JSPath

JSPath is a domain-specific language (DSL) that enables you to navigate and find data within your JSON documents. Using JSPath, you can select items of JSON in order to retrieve the data they contain.

JSPath 是一种域特定语言 (DSL),使您能够在 JSON 文档中导航和查找数据。使用 JSPath,您可以选择 JSON 项以检索它们包含的数据。

JSPath for JSON like an XPath for XML.

JSON 的 JSPath 就像 XML 的 XPath。

It is heavily optimized both for Node.js and modern browsers.

它针对 Node.js 和现代浏览器进行了大量优化。

回答by Christian Grün

XQuery can be used to query JSON, provided that the processor offers JSON support. This is a straightforward example how BaseX can be used to find objects with "id" = 1:

XQuery 可用于查询 JSON,前提是处理器提供 JSON 支持。这是一个简单的示例,说明如何使用 BaseX 查找“id”= 1 的对象:

json:parse('[
    { "id": 1, "name": "One", "objects": [
        { "id": 1, "name": "Response 1", "objects": [ "etc." ] }
    ]}
]')//value[.//id = 1]

回答by peak

Is there some kind of query language ...

是否有某种查询语言...

jqdefines a JSON query language that is very similar to JSONPath -- see https://github.com/stedolan/jq/wiki/For-JSONPath-users

JQ限定ĴSON query语言非常类似于JSONPath -见https://github.com/stedolan/jq/wiki/For-JSONPath-users

... [which] I can used to find an item in [0].objects where id = 3?

... [which] 我可以用来在 [0].objects 中找到一个项目,其中 id = 3?

I'll assume this means: find all JSON objects under the specified key with id == 3, no matter where the object may be. A corresponding jq query would be:

我假设这意味着:在 id == 3 的指定键下查找所有 JSON 对象,无论对象在哪里。相应的 jq 查询将是:

.[0].objects | .. | objects | select(.id==3)

where "|" is the pipe-operator (as in command shell pipes), and where the segment ".. | objects" corresponds to "no matter where the object may be".

其中“|” 是管道操作符(如在命令外壳管道中),其中段“.. | objects”对应于“无论对象在哪里”。

The basics of jq are largely obvious or intuitive or at least quite simple, and most of the rest is easy to pick up if you're at all familiar with command-shell pipes. The jq FAQhas pointers to tutorials and the like.

jq 的基础知识在很大程度上是显而易见的或直观的,或者至少非常简单,如果您完全熟悉命令外壳管道,那么其余的大部分内容都很容易掌握。jq常见问题有指向教程等的指针。

jq is also like SQL in that it supports CRUD operations, though the jq processor never overwrites its input. jq can also handle streams of JSON entities.

jq 也类似于 SQL,因为它支持 CRUD 操作,尽管 jq 处理器从不覆盖其输入。jq 还可以处理 JSON 实体流。

Two other criteria you might wish to consider in assessing a JSON-oriented query language are:

在评估面向 JSON 的查询语言时,您可能希望考虑的另外两个标准是:

  • does it support regular expressions? (jq 1.5 has comprehensive support for PCRE regex)
  • is it Turing-complete? (yep)
  • 它支持正则表达式吗?(jq 1.5 全面支持 PCRE 正则表达式)
  • 图灵完备吗?(是的)

回答by Epoc

Defiant.jslooks also pretty cool, here's a simple example:

Defiant.js看起来也很酷,这是一个简单的例子:

var obj = {
        "car": [
            {"id": 10, "color": "silver", "name": "Volvo"},
            {"id": 11, "color": "red",    "name": "Saab"},
            {"id": 12, "color": "red",    "name": "Peugeot"},
            {"id": 13, "color": "yellow", "name": "Porsche"}
        ],
        "bike": [
            {"id": 20, "color": "black", "name": "Cannondale"},
            {"id": 21, "color": "red",   "name": "Shimano"}
        ]
    },
    search = JSON.search(obj, '//car[color="yellow"]/name');

console.log( search );
// ["Porsche"]

var reds = JSON.search(obj, '//*[color="red"]');

for (var i=0; i<reds.length; i++) {
    console.log( reds[i].name );
}
// Saab
// Peugeot
// Shimano

回答by Ali

Jselis awesome and is based on a real XPath engine. It allows you to create XPath expressions to find any type of JavaScript data, not just objects (strings too).

Jsel很棒,并且基于真正的 XPath 引擎。它允许您创建 XPath 表达式来查找任何类型的 JavaScript 数据,而不仅仅是对象(字符串也是)。

You can create custom schemas and mappings to give you complete control over how your data is walkable by the XPath engine. A schema is a way of defining how elements, children, attributes, and node values are defined in your data. Then you can create your own expressions to suit.

您可以创建自定义模式和映射,以完全控制 XPath 引擎如何遍历您的数据。模式是一种定义如何在数据中定义元素、子项、属性和节点值的方法。然后,您可以创建自己的表达式以适应。

Given you had a variable called datawhich contained the JSON from the question, you could use jsel to write:

鉴于您有一个名为的变量data,其中包含问题中的 JSON,您可以使用 jsel 编写:

jsel(data).select("//*[@id=3]")

This will return any node with an idattribute of 3. An attribute is any primitive (string, number, date, regex) value within an object.

这将返回id属性为 3 的任何节点。属性是对象内的任何原始(字符串、数字、日期、正则表达式)值。

回答by karlfreeman

Json Pointerseem's to be getting growing support too.

Json Pointer似乎也得到了越来越多的支持。