有 JSON 的查询语言吗?

发布于 2024-07-17 07:59:53 字数 808 浏览 6 评论 0原文

是否有(大致)SQL 或类似 XQuery 的语言用于查询 JSON?

我正在考虑可以很好地映射到 JSON 的非常小的数据集,这样可以轻松回答诸如“X 的所有值是多少,其中 Y > 3”之类的查询,或者执行通常的 SUM / COUNT 类型操作。

作为完全虚构的示例,如下所示:

[{"x": 2, "y": 0}}, {"x": 3, "y": 1}, {"x": 4, "y": 1}]

SUM(X) WHERE Y > 0     (would equate to 7)
LIST(X) WHERE Y > 0    (would equate to [3,4])

我认为这在客户端和服务器端都可以工作,结果将转换为适当的特定于语言的数据结构(或者可能保留为 JSON)

快速谷歌搜索表明人们已经考虑过并实现了一些东西(JAQL),但是似乎还没有出现标准用法或库集。 虽然每个功能单独实现都相当简单,但如果有人已经正确完成了,我不想重新发明轮子。

有什么建议么?

编辑:这可能确实是一个坏主意,或者 JSON 对于我的想法来说可能太通用了。想要一种查询语言而不是直接根据需要直接执行求和/等功能的原因是我希望构建基于用户输入动态查询。 有点像“我们不需要 SQL,我们可以只编写我们需要的函数”的论点。 最终,要么会失控,要么你最终会编写自己的 SQL 版本,因为你将它推得越来越远。 (好吧,我知道这有点愚蠢,但你明白了..)

Is there a (roughly) SQL or XQuery-like language for querying JSON?

I'm thinking of very small datasets that map nicely to JSON where it would be nice to easily answer queries such as "what are all the values of X where Y > 3" or to do the usual SUM / COUNT type operations.

As completely made-up example, something like this:

[{"x": 2, "y": 0}}, {"x": 3, "y": 1}, {"x": 4, "y": 1}]

SUM(X) WHERE Y > 0     (would equate to 7)
LIST(X) WHERE Y > 0    (would equate to [3,4])

I'm thinking this would work both client-side and server-side with results being converted to the appropriate language-specific data structure (or perhaps kept as JSON)

A quick Googling suggests that people have thought about it and implemented a few things (JAQL), but it doesn't seem like a standard usage or set of libraries has emerged yet. While each function is fairly trivial to implement on its own, if someone has already done it right I don't want to re-invent the wheel.

Any suggestions?

Edit: This may indeed be a bad idea or JSON may be too generic a format for what I'm thinking.. The reason for wanting a query language instead of just doing the summing/etc functions directly as needed is that I hope to build the queries dynamically based on user-input. Kinda like the argument that "we don't need SQL, we can just write the functions we need". Eventually that either gets out of hand or you end up writing your own version of SQL as you push it further and further. (Okay, I know that is a bit of a silly argument, but you get the idea..)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

沐歌 2024-07-24 07:59:53

2022 年 9 月编辑:

JMESPath 似乎是最广泛使用,增长最快,并且评论最佳 的替代方案。 它具有许多功能,包括“where”样式过滤器

原文:

当然,怎么样:

它们似乎都在进行中,但在某种程度上起作用。 它们在概念上也类似于 XPath 和 XQuery; 尽管 XML 和 JSON 具有不同的概念模型(层次结构与对象/结构)。

2015 年 9 月编辑:

实际上现在有 JSON 指针 标准,允许非常简单且高效地遍历JSON 内容。 它不仅被正式指定,而且还得到许多 JSON 库的支持。 因此,我将其称为真正有用的标准,尽管由于其有限的表达能力,它本身可能会或可能不会被视为查询语言。

EDIT Sept 2022:

JMESPath seems to be the most widely-used, fastest-growing, and best-reviewed of alternatives for this. It has many features, including "where"-style filters.

ORIGINAL:

Sure, how about:

They all seem to be a bit work in progress, but work to some degree. They are also similar to XPath and XQuery conceptually; even though XML and JSON have different conceptual models (hierarchic vs object/struct).

EDIT Sept 2015:

Actually there is now JSON Pointer standard that allows very simple and efficient traversal of JSON content. It is not only formally specified, but also supported by many JSON libraries. So I would call it actual real useful standard, although due to its limited expressiveness it may or may not be considered Query Language per se.

夏日浅笑〃 2024-07-24 07:59:53

更新:XQuery 3.1 可以查询 XML 或 JSON - 或同时查询两者。 XPath 3.1 也可以。

该列表正在不断增长:

  • JSONiq(基于 XQuery)
  • UNQL(如 SQL)
  • JaQL(功能)
  • < a href="http://goessner.net/articles/JsonPath/" rel="noreferrer">JsonPath (类似 XPath)
  • Json 查询(类似于 XPath)
  • GraphQL(基于模板,输入)
  • JMESpath

Update: XQuery 3.1 can query either XML or JSON - or both together. And XPath 3.1 can too.

The list is growing:

仙女山的月亮 2024-07-24 07:59:53

我推荐我正在开发的项目 jLinq。 我正在寻找反馈,因此我有兴趣听听您的想法。

如果让您可以像在 LINQ 中那样编写查询...

var results = jLinq.from(records.users)

    //you can join records
    .join(records.locations, "location", "locationId", "id")

    //write queries on the data
    .startsWith("firstname", "j")
    .or("k") //automatically remembers field and command names

    //even query joined items
    .equals("location.state", "TX")

    //and even do custom selections
    .select(function(rec) {
        return {
            fullname : rec.firstname + " " + rec.lastname,
            city : rec.location.city,
            ageInTenYears : (rec.age + 10)
        };
    });

它也是完全可扩展的!

该文档仍在编写中,但您仍然可以在线尝试。

I'd recommend my project I'm working on called jLinq. I'm looking for feedback so I'd be interested in hearing what you think.

If lets you write queries similar to how you would in LINQ...

var results = jLinq.from(records.users)

    //you can join records
    .join(records.locations, "location", "locationId", "id")

    //write queries on the data
    .startsWith("firstname", "j")
    .or("k") //automatically remembers field and command names

    //even query joined items
    .equals("location.state", "TX")

    //and even do custom selections
    .select(function(rec) {
        return {
            fullname : rec.firstname + " " + rec.lastname,
            city : rec.location.city,
            ageInTenYears : (rec.age + 10)
        };
    });

It's fully extensible too!

The documentation is still in progress, but you can still try it online.

岁吢 2024-07-24 07:59:53

JMESPath 工作起来确实非常简单和良好:http://jmespath.org/
它有完整的规范和多种语言的库。 Amazon 在 AWS 命令​​行界面中使用它,因此它必须非常稳定。

语法示例:

// 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(', ', @)

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

JMESPath works really quite easy and well: http://jmespath.org/.
It has a thorough specification, and libraries for multiple languages. It is being used by Amazon in the AWS command line interface, so it’s got to be quite stable.

Syntax Examples:

// 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(', ', @)

There are plenty more live examples you can play with in the docs.

無處可尋 2024-07-24 07:59:53

jq 是一种 JSON q查询语言,主要用于命令行,但与多种编程语言(Java、node.js、php...)绑定,甚至可以通过 jq-web。 jq 基于 C 的实现通常称为“jq”,基于 Go 的版本为 "gojq"。

以下是基于原始问题的一些说明,以 JSON 为例:

 [{"x": 2, "y": 0}}, {"x": 3, "y": 1}, {"x": 4, "y": 1}]

SUM(X),其中 Y > 0(相当于 7)

map(select(.y > 0)) | add

列表(X),其中 Y > 0(等于[3,4])

map(.y > 0)

jq 语法扩展 JSON 语法

每个 JSON 表达式都是有效的 jq 表达式,以及诸如 [1, (1+1)] 和 {"a" 之类的表达式: (1+1)}` 说明 jq 如何扩展 JSON 语法。

一个更有用的示例是 jq 表达式:

{a,b}

给定 JSON 值 {"a":1, "b":2, "c": 3},其计算结果为 {"a “:1,”b“:2}

jq is a JSON query language, mainly intended for the command-line but with bindings to a wide range of programming languages (Java, node.js, php, ...) and even available in the browser via jq-web. The C-based implementation of jq is generally known as "jq", and the Go-based version as "gojq".

Here are some illustrations based on the original question, which gave this JSON as an example:

 [{"x": 2, "y": 0}}, {"x": 3, "y": 1}, {"x": 4, "y": 1}]

SUM(X) WHERE Y > 0 (would equate to 7)

map(select(.y > 0)) | add

LIST(X) WHERE Y > 0 (would equate to [3,4])

map(.y > 0)

jq syntax extends JSON syntax

Every JSON expression is a valid jq expression, and expressions such as [1, (1+1)] and {"a": (1+1)}` illustrate how jq extends JSON syntax.

A more useful example is the jq expression:

{a,b}

which, given the JSON value {"a":1, "b":2, "c": 3}, evaluates to {"a":1, "b":2}.

木格 2024-07-24 07:59:53

内置的 array.filter() 方法 使大多数所谓的 javascript 查询库变得过时。

您可以在委托中放置尽可能多的条件:简单比较、startsWith 等。我还没有测试过,但您也可以嵌套过滤器来查询内部收藏。

The built-in array.filter() method makes most of these so-called javascript query libraries obsolete

You can put as many conditions inside the delegate as you can imagine: simple comparison, startsWith, etc. I haven't tested but you could probably nest filters too for querying inner collections.

木森分化 2024-07-24 07:59:53

另一种看待这个问题的方法是使用 mongoDB 您可以存储您的mongo 中的 JSON,然后通过 mongodb 查询语法进行查询。

Another way to look at this would be to use mongoDB You can store your JSON in mongo and then query it via the mongodb query syntax.

不必了 2024-07-24 07:59:53

如果您使用 .NET,则 Json.NET 支持 LINQ 查询JSON。 此帖子有一些例子。 它支持过滤、映射、分组等。

If you are using .NET then Json.NET supports LINQ queries over the top of JSON. This post has some examples. It supports filtering, mapping, grouping, etc.

扮仙女 2024-07-24 07:59:53

ObjectPath 是一种简单且轻量级的查询语言,适用于复杂或未知结构的 JSON 文档。 它类似于 XPath 或 JSONPath,但由于嵌入式算术计算、比较机制和内置函数,它的功能更加强大。

Example

Python 版本已成熟并用于生产。 JS 仍处于测试阶段。

也许在不久的将来我们将提供一个成熟的 Javascript 版本。 我们还希望进一步开发它,以便它可以作为 Mongo 查询的更简单的替代方案。

ObjectPath is simple and ligthweigth query language for JSON documents of complex or unknown structure. It's similar to XPath or JSONPath, but much more powerful thanks to embedded arithmetic calculations, comparison mechanisms and built-in functions.

Example

Python version is mature and used in production. JS is still in beta.

Probably in the near future we will provide a full-fledged Javascript version. We also want to develop it further, so that it could serve as a simpler alternative to Mongo queries.

戏蝶舞 2024-07-24 07:59:53

好吧,这篇文章有点老了,但是...如果你想在 JS 对象上用原生 JSON(或 JS 对象)进行类似 SQL 的查询,请看一下 https://github.com/deitch/searchjs

它既是完全用 JSON 编写的 jsql 语言,也是一个参考实现。 您可以说,“我想查找数组中具有 name===John” &&age===25 的所有对象,如下所示:

{name:"John",age:25,_join:"AND"}

参考实现 searchjs 在浏览器以及节点 npm 包中工作

npm install searchjs

它还可以执行复杂的连接和求反(NOT)之类的操作,

它本身不会进行求和或计数,但在外部执行这些操作可能更容易。

OK, this post is a little old, but... if you want to do SQL-like query in native JSON (or JS objects) on JS objects, take a look at https://github.com/deitch/searchjs

It is both a jsql language written entirely in JSON, and a reference implementation. You can say, "I want to find all object in an array that have name==="John" && age===25 as:

{name:"John",age:25,_join:"AND"}

The reference implementation searchjs works in the browser as well as as a node npm package

npm install searchjs

It can also do things like complex joins and negation (NOT). It natively ignores case.

It doesn't yet do summation or count, but it is probably easier to do those outside.

躲猫猫 2024-07-24 07:59:53

如果你想使用纯 JavaScript 试试这个:

var object = { result: { data: { point1: "x", value: 2 }, foo: { bar: 7 } } },
    path = 'result.data.value',
    getValue = (o, p) => p.split('.').reduce((r, k) => r[k], o);

console.log(getValue(object, path));

if you want to use pure javascript try this:

var object = { result: { data: { point1: "x", value: 2 }, foo: { bar: 7 } } },
    path = 'result.data.value',
    getValue = (o, p) => p.split('.').reduce((r, k) => r[k], o);

console.log(getValue(object, path));

沫雨熙 2024-07-24 07:59:53

这里有一些简单的 javascript 库也可以实现这一点:

  • Dollar Q 是一个很好的轻量级库。 它对 jQuery 流行的链接语法有一种熟悉的感觉,并且只有 373 个 SLOC。
  • SpahQL 是一种功能齐全的查询语言,其语法类似于 XPath (主页Github
  • jFunk 是一种正在进行的查询语言,其语法类似于 CSS/ jQuery 选择器。它看起来很有前途,但除了最初的提交之外还没有任何进展。

  • 。 href="https://stedolan.github.io/jq/" rel="nofollow">jq 命令行工具 具有简洁的语法,但不幸的是它是 ac 库示例用法:

    <代码>< package.json jq '.dependencies | 到_条目 | .[]| 选择(.value |startswith(“git”))| .key'

Here's some simple javascript libraries that will also do the trick:

  • Dollar Q is a nice lightweight library. It has a familiar feel to the chaining syntax made popular by jQuery and is only 373 SLOC.
  • SpahQL is a fully featured query language with a syntax similar to XPath (Homepage, Github
  • jFunk is an in progress query language, with a syntax similar to CSS/jQuery selectors. It looked promising, but hasn't had any development beyond its in initial commit.

  • (added 2014): the jq command line tool has a neat syntax, but unfortunately it is a c library. Example usage:

    < package.json jq '.dependencies | to_entries | .[] | select(.value | startswith("git")) | .key'

避讳 2024-07-24 07:59:53

MongoDB 中,这就是它的工作方式(在 mongo shell 中,存在您选择的语言的驱动程序)。

db.collection.insert({"x": 2, "y": 0}); // notice the ':' instead of ','
db.collection.insert({"x": 3, "y": 1});
db.collection.insert({"x": 4, "y": 1});

db.collection.aggregate([{$match: {"y": {$gt: 0}}}, 
                         {$group: {_id: "sum", sum: {$sum: "$x"}}}]);
db.collection.aggregate([{$match: {"y": {$gt: 0}}}, 
                         {$group: {_id: "list", list: {$push: "$x"}}}]);

前三个命令将数据插入到您的集合中。 (只需启动 mongod 服务器并连接 mongo 客户端即可。)

接下来的两个处理数据。 $match 过滤器,$group 应用sum 和 list

In MongoDB, this is how it would work (in the mongo shell, there exist drivers for a language of your choice).

db.collection.insert({"x": 2, "y": 0}); // notice the ':' instead of ','
db.collection.insert({"x": 3, "y": 1});
db.collection.insert({"x": 4, "y": 1});

db.collection.aggregate([{$match: {"y": {$gt: 0}}}, 
                         {$group: {_id: "sum", sum: {$sum: "$x"}}}]);
db.collection.aggregate([{$match: {"y": {$gt: 0}}}, 
                         {$group: {_id: "list", list: {$push: "$x"}}}]);

The first three commands insert the data into your collection. (Just start the mongod server and connect with the mongo client.)

The next two process the data. $match filters, $group applies the sum and list, respectively.

安静被遗忘 2024-07-24 07:59:53

查看 https://github.com/niclasko/Cypher.js (注意:我' m 作者)

它是 Cypher 图数据库查询语言和图数据库的零依赖 Javascript 实现。 它在浏览器中运行(使用 Firefox、Chrome、IE 进行测试)。

与问题相关。 它可用于查询 JSON 端点:

load json from "http://url/endpoint" as l return l limit 10

以下是查询复杂 JSON 文档并对其进行分析的示例:

Cypher.js JSON 查询示例

Check out https://github.com/niclasko/Cypher.js (note: I'm the author)

It's a zero-dependency Javascript implementation of the Cypher graph database query language along with a graph database. It runs in the browser (tested with Firefox, Chrome, IE).

With relevance to the question. It can be used to query JSON endpoints:

load json from "http://url/endpoint" as l return l limit 10

Here's an example of querying a complex JSON document and performing analysis on it:

Cypher.js JSON query example

甜警司 2024-07-24 07:59:53

您可以使用 linq.js

这允许使用对象数据集中的聚合和选择,就像其他结构数据一样。

var data = [{ x: 2, y: 0 }, { x: 3, y: 1 }, { x: 4, y: 1 }];

// SUM(X) WHERE Y > 0     -> 7
console.log(Enumerable.From(data).Where("$.y > 0").Sum("$.x"));

// LIST(X) WHERE Y > 0    -> [3, 4]
console.log(Enumerable.From(data).Where("$.y > 0").Select("$.x").ToArray());
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>

You could use linq.js.

This allows to use aggregations and selectings from a data set of objects, as other structures data.

var data = [{ x: 2, y: 0 }, { x: 3, y: 1 }, { x: 4, y: 1 }];

// SUM(X) WHERE Y > 0     -> 7
console.log(Enumerable.From(data).Where("$.y > 0").Sum("$.x"));

// LIST(X) WHERE Y > 0    -> [3, 4]
console.log(Enumerable.From(data).Where("$.y > 0").Select("$.x").ToArray());
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>

迷路的信 2024-07-24 07:59:53

据我所知,SphQL 是其中最有前途且经过深思熟虑的。 我强烈建议您检查一下。

SpahQL is the most promising and well thought out of these, as far as I can tell. I highly recommend checking it out.

爱*していゐ 2024-07-24 07:59:53

我刚刚完成了客户端 JS-lib (defiant.js) 的可发布版本,它可以满足您的需求。 使用 defiant.js,您可以使用熟悉的 XPath 表达式查询 JSON 结构(没有 JSONPath 中的新语法表达式)。

其工作原理示例(在浏览器中查看 http://defiantjs.com/ defiant.js/demo/sum.avg.htm):

var data = [
       { "x": 2, "y": 0 },
       { "x": 3, "y": 1 },
       { "x": 4, "y": 1 },
       { "x": 2, "y": 1 }
    ],
    res = JSON.search( data, '//*[ y > 0 ]' );

console.log( res.sum('x') );
// 9
console.log( res.avg('x') );
// 3
console.log( res.min('x') );
// 2
console.log( res.max('x') );
// 4

如您所见,DefiantJS 使用搜索函数扩展了全局对象 JSON,并使用聚合函数传递返回的数组。 DefiantJS 包含一些其他功能,但这些功能超出了本主题的范围。
无论如何,您都可以使用客户端 XPath Evaluator 来测试该库。 我认为不熟悉 XPath 的人会发现这个评估器很有用。
http://defiantjs.com/#xpath_evaluator

有关 defiant.js 的更多信息
http://defiantjs.com/
https://github.com/hbi99/defiant.js

我希望你觉得它有用.. 。
问候

I've just finished a releaseable version of a clientside JS-lib (defiant.js) that does what you're looking for. With defiant.js, you can query a JSON structure with the XPath expressions you're familiar with (no new syntax expressions as in JSONPath).

Example of how it works (see it in browser here http://defiantjs.com/defiant.js/demo/sum.avg.htm):

var data = [
       { "x": 2, "y": 0 },
       { "x": 3, "y": 1 },
       { "x": 4, "y": 1 },
       { "x": 2, "y": 1 }
    ],
    res = JSON.search( data, '//*[ y > 0 ]' );

console.log( res.sum('x') );
// 9
console.log( res.avg('x') );
// 3
console.log( res.min('x') );
// 2
console.log( res.max('x') );
// 4

As you can see, DefiantJS extends the global object JSON with a search function and the returned array is delivered with aggregate functions. DefiantJS contains a few other functionalities but those are out of the scope for this subject.
Anywho, you can test the lib with a clientside XPath Evaluator. I think people not familiar with XPath will find this evaluator useful.
http://defiantjs.com/#xpath_evaluator

More information about defiant.js
http://defiantjs.com/
https://github.com/hbi99/defiant.js

I hope you find it useful...
Regards

悸初 2024-07-24 07:59:53
  1. Google 有一个名为 lovefield 的项目; 刚刚发现它,它看起来很有趣,尽管它比仅仅添加下划线或 lodash 更复杂。

    https://github.com/google/lovefield

Lovefield 是一个用纯 JavaScript 编写的关系查询引擎。 它
还提供在浏览器端保存数据的帮助,例如
使用 IndexedDB 在本地存储数据。 它提供类似 SQL 的语法并且
跨浏览器工作(目前支持 Chrome 37+、Firefox 31+、IE
10+ 和 Safari 5.1+...


  1. 这个领域最近另一个有趣的条目称为jinqJs

    http://www.jinqjs.com/

    简要回顾一下示例,它看起来很有希望,并且API 文档 看起来写得很好。


function isChild(row) {
  return (row.Age < 18 ? 'Yes' : 'No');
}

var people = [
  {Name: 'Jane', Age: 20, Location: 'Smithtown'},
  {Name: 'Ken', Age: 57, Location: 'Islip'},
  {Name: 'Tom', Age: 10, Location: 'Islip'}
];

var result = new jinqJs()
  .from(people)
  .orderBy('Age')
  .select([{field: 'Name'}, 
     {field: 'Age', text: 'Your Age'}, 
     {text: 'Is Child', value: isChild}]);

jinqJs是一个小型、简单、轻量级且可扩展的javaScript
没有依赖项的库。 jinqJs 提供了一种简单的方法
在 JavaScript 数组、集合和 Web 上执行类似 SQL 的查询
返回 JSON 响应的服务。 jinqJs 和微软的类似
.Net 的 Lambda 表达式,它提供了类似的功能
使用类似 SQL 的语法和谓词功能来查询集合。
jinqJs 的目的是为程序员提供类似 SQL 的体验
熟悉 LINQ 查询。

  1. Google has a project called lovefield; just found out about it, and it looks interesting, though it is more involved than just dropping in underscore or lodash.

    https://github.com/google/lovefield

Lovefield is a relational query engine written in pure JavaScript. It
also provides help with persisting data on the browser side, e.g.
using IndexedDB to store data locally. It provides SQL-like syntax and
works cross-browser (currently supporting Chrome 37+, Firefox 31+, IE
10+, and Safari 5.1+...


  1. Another interesting recent entry in this space called jinqJs.

    http://www.jinqjs.com/

    Briefly reviewing the examples, it looks promising, and the API document appears to be well written.


function isChild(row) {
  return (row.Age < 18 ? 'Yes' : 'No');
}

var people = [
  {Name: 'Jane', Age: 20, Location: 'Smithtown'},
  {Name: 'Ken', Age: 57, Location: 'Islip'},
  {Name: 'Tom', Age: 10, Location: 'Islip'}
];

var result = new jinqJs()
  .from(people)
  .orderBy('Age')
  .select([{field: 'Name'}, 
     {field: 'Age', text: 'Your Age'}, 
     {text: 'Is Child', value: isChild}]);

jinqJs is a small, simple, lightweight and extensible javaScript
library that has no dependencies. jinqJs provides a simple way to
perform SQL like queries on javaScript arrays, collections and web
services that return a JSON response. jinqJs is similar to Microsoft's
Lambda expression for .Net, and it provides similar capabilities to
query collections using a SQL like syntax and predicate functionality.
jinqJs’s purpose is to provide a SQL like experience to programmers
familiar with LINQ queries.

俏︾媚 2024-07-24 07:59:53

PythonQL 提供了一种嵌入式语法,恕我直言,这是对 SQL 的改进,主要是因为 groupwindowwherelet等可以自由混合。

$ cat x.py
#coding: pythonql
data = [{"x": 2, "y": 0}, {"x": 3, "y": 1}, {"x": 4, "y": 1}]
q = [x match {'x': as x, 'y': as y} in data where y > 0]
print(sum(q))
print(list(q))

q = [x match {'x': as x, 'y': as y} as d in data where d['y'] > 0]
print(sum(q))

此代码显示了您的问题的两个不同答案,具体取决于您需要处理整个结构还是仅处理值。 执行会给你预期的结果。

$ python x.py
7
[3, 4]
7

PythonQL offers an embedded syntax that IMHO is an improvement on SQL, principally because group, window, where, let, etc. can be freely intermixed.

$ cat x.py
#coding: pythonql
data = [{"x": 2, "y": 0}, {"x": 3, "y": 1}, {"x": 4, "y": 1}]
q = [x match {'x': as x, 'y': as y} in data where y > 0]
print(sum(q))
print(list(q))

q = [x match {'x': as x, 'y': as y} as d in data where d['y'] > 0]
print(sum(q))

This code shows two different answers to your question, depending on your need to handle the entire structure or just the value. Execution gives you the expected result.

$ python x.py
7
[3, 4]
7
或十年 2024-07-24 07:59:53

JSONata (https://jsonata.org/) 是另一种选择。 你的例子将转化为:

// input:
[
  {"x": 2, "y": 0}, 
  {"x": 3, "y": 1}, 
  {"x": 4, "y": 1}
]

// LIST(X) WHERE Y > 0     yields [3, 4]
$[y>0].x

// SUM(X) WHERE Y > 0      yields 7
$sum($[y>0].x)

JSONata (https://jsonata.org/) is another option. Your examples would translate to:

// input:
[
  {"x": 2, "y": 0}, 
  {"x": 3, "y": 1}, 
  {"x": 4, "y": 1}
]

// LIST(X) WHERE Y > 0     yields [3, 4]
$[y>0].x

// SUM(X) WHERE Y > 0      yields 7
$sum($[y>0].x)
音盲 2024-07-24 07:59:53

我会支持仅使用您自己的 javascript 的概念,但对于更复杂的东西,您可以查看 dojo 数据。 还没有使用过它,但看起来它大致为您提供了您正在寻找的查询界面。

I'll second the notion of just using your own javascript, but for something a bit more sophisticated you might look at dojo data. Haven't used it but it looks like it gives you roughly the kind of query interface you're looking for.

佞臣 2024-07-24 07:59:53

当前 Jaql 实现的目标是使用 Hadoop 集群进行大数据处理,因此它可能超出您的需要。 然而,它可以在没有 Hadoop 集群的情况下轻松运行(但仍然需要 Hadoop 代码及其依赖项进行编译,其中大部分都包含在内)。 可以嵌入 Javascript 和浏览器中的 Jaql 小型实现将是该项目的一个很好的补充。

您上面的示例很容易用 jaql 编写:

$data = [{"x": 2, "y": 0}, {"x": 3, "y": 1}, {"x": 4, "y": 1}];

$data -> filter $.y > 0 -> transform $.x -> sum(); // 7

$data -> filter $.y > 0 -> transform $.x; // [3,4]

当然,还有更多。 例如:

// Compute multiple aggregates and change nesting structure:
$data -> group by $y = $.y into { $y, s:sum($[*].x), n:count($), xs:$[*].x}; 
    // [{ "y": 0, "s": 2, "n": 1, "xs": [2]   },
    //  { "y": 1, "s": 7, "n": 2, "xs": [3,4] }]

// Join multiple data sets:
$more = [{ "y": 0, "z": 5 }, { "y": 1, "z": 6 }];
join $data, $more where $data.y == $more.y into {$data, $more};
    // [{ "data": { "x": 2, "y": 0 }, "more": { "y": 0, "z": 5 }},
    //  { "data": { "x": 3, "y": 1 }, "more": { "y": 1, "z": 6 }},
    //  { "data": { "x": 4, "y": 1 }, "more": { "y": 1, "z": 6 }}]

Jaql 可以在 http://code.google.com/p/jaql 下载/讨论/

The current Jaql implementation targets large data processing using a Hadoop cluster, so it might be more than you need. However, it runs easily without a Hadoop cluster (but still requires the Hadoop code and its dependencies to get compiled, which are mostly included). A small implementation of Jaql that could be embedded in Javascript and the a browser would be a great addition to the project.

Your examples above are easily written in jaql:

$data = [{"x": 2, "y": 0}, {"x": 3, "y": 1}, {"x": 4, "y": 1}];

$data -> filter $.y > 0 -> transform $.x -> sum(); // 7

$data -> filter $.y > 0 -> transform $.x; // [3,4]

Of course, there's much more too. For example:

// Compute multiple aggregates and change nesting structure:
$data -> group by $y = $.y into { $y, s:sum($[*].x), n:count($), xs:$[*].x}; 
    // [{ "y": 0, "s": 2, "n": 1, "xs": [2]   },
    //  { "y": 1, "s": 7, "n": 2, "xs": [3,4] }]

// Join multiple data sets:
$more = [{ "y": 0, "z": 5 }, { "y": 1, "z": 6 }];
join $data, $more where $data.y == $more.y into {$data, $more};
    // [{ "data": { "x": 2, "y": 0 }, "more": { "y": 0, "z": 5 }},
    //  { "data": { "x": 3, "y": 1 }, "more": { "y": 1, "z": 6 }},
    //  { "data": { "x": 4, "y": 1 }, "more": { "y": 1, "z": 6 }}]

Jaql can be downloaded/discussed at http://code.google.com/p/jaql/

七度光 2024-07-24 07:59:53

您还可以使用 Underscore.js 它基本上是一个 swiss-knife 库来操作集合。 使用 _.filter_.pluck, _.reduce 你可以进行类似SQL的查询。

var data = [{"x": 2, "y": 0}, {"x": 3, "y": 1}, {"x": 4, "y": 1}];

var posData = _.filter(data, function(elt) { return elt.y > 0; });
// [{"x": 3, "y": 1}, {"x": 4, "y": 1}]

var values = _.pluck(posData, "x");
// [3, 4]

var sum = _.reduce(values, function(a, b) { return a+b; });
// 7

Underscore.js 可在客户端和服务器端运行,是一个著名的库。

您还可以使用 Lo-Dash,它是 Underscore.js 的一个分支,具有更好的性能。

You can also use Underscore.js which is basically a swiss-knife library to manipulate collections. Using _.filter, _.pluck, _.reduce you can do SQL-like queries.

var data = [{"x": 2, "y": 0}, {"x": 3, "y": 1}, {"x": 4, "y": 1}];

var posData = _.filter(data, function(elt) { return elt.y > 0; });
// [{"x": 3, "y": 1}, {"x": 4, "y": 1}]

var values = _.pluck(posData, "x");
// [3, 4]

var sum = _.reduce(values, function(a, b) { return a+b; });
// 7

Underscore.js works both client-side and server-side and is a notable library.

You can also use Lo-Dash which is a fork of Underscore.js with better performances.

软糯酥胸 2024-07-24 07:59:53

只要有可能,我都会将所有查询转移到服务器后端(SQL DB 或其他本机数据库类型)。 原因是查询会更快、更优化。

我知道 jSON 可以是独立的,并且拥有查询语言可能有 +/-,但如果您从后端检索数据到浏览器,我看不到优势,就像大多数 JSON 用例一样。 在后端进行查询和过滤以获得所需的尽可能小的数据。

如果出于某种原因您需要在前端进行查询(主要是在浏览器中),那么我建议只使用 array.filter (为什么要发明其他东西?)。

也就是说,我认为更有用的是 json 的转换 API...它们更有用,因为一旦您拥有数据,您可能希望以多种方式显示它。 然而,同样,如果您使用服务器<-->客户端模型,您可以在服务器上比在客户端上完成大部分工作(这可以更容易扩展)。

只值我的2便士!

Whenever possible I would shift all of the querying to the backend on the server (to the SQL DB or other native database type). Reason being is that it will be quicker and more optimized to do the querying.

I know that jSON can be stand alone and there may be +/- for having a querying language but I cannot see the advantage if you are retrieving data from the backend to a browser, as most of the JSON use cases. Query and filter at the backend to get as small a data that is needed.

If for whatever reason you need to query at the front-end (mostly in a browser) then I would suggest just using array.filter (why invent something else?).

That said what I think would be more useful is a transformation API for json...they are more useful since once you have the data you may want to display it in a number of ways. However, again, you can do much of this on the server (which can be much easier to scale) than on the client - IF you are using server<-->client model.

Just my 2 pence worth!

今天小雨转甜 2024-07-24 07:59:53

我是一种新的 JSON 查询语言的开发人员,称为 ~Q(发音为“unquery”)。 它旨在解决其他 JSON 查询语言的许多缺点,并平衡易用性和表达能力。 作为主要开发人员,我当然有偏见,但你可以检查一下并自行决定:

https ://github.com/xcite-db/Unquery

至于OP的示例,〜Q中的查询将是:

{
    "example1:[]" : "$sum(x)?y>0",
    "example2:[]" : ["x?y>0"]
}

I am the developer of a new query language for JSON, called ~Q (pronounced "unquery"). It was designed to address many of the shortcomings of other JSON query languages, and balance ease of use and expressive power. As the main developer, I am biased, of course, but you can check it out and decide for yourself:

https://github.com/xcite-db/Unquery

As for the OP's examples, the queries in ~Q would be:

{
    "example1:[]" : "$sum(x)?y>0",
    "example2:[]" : ["x?y>0"]
}
孤独陪着我 2024-07-24 07:59:53

我使用 SQLite 来实现: https://sqlite.org/json1.html

这很好,因为你可以使用实际 SQL 语言,并且 SQLite 非常快。

首先,我创建一个临时表:

create temp table data as select value from json_each(readfile('data.json'))

然后使用 SQLite JSON 函数:

select value->'$.foo' foo, count(value->'$.bar') nbar from data group by foo 

I use SQLite for that: https://sqlite.org/json1.html

It's nice because you can use the actual SQL language and SQLite is very fast.

First I create a temp table:

create temp table data as select value from json_each(readfile('data.json'))

Then use the SQLite JSON functions:

select value->'$.foo' foo, count(value->'$.bar') nbar from data group by foo 
美人骨 2024-07-24 07:59:53

如果你使用Python,有Mini开源版本的MongoDB,
MontyDB https://github.com/davidlatwe/montydb
它在 github 上有超过 500 多个 star,并且得到 JetBrains 的支持。

from montydb.utils import MontyList
response = [
    {'namespace': 'dash_mantine_components',
     'props': {'checked': True,
               'id': {'index': 0, 'type': 'checkbox'},
               'label': 'My first to do'},
     'type': 'Checkbox'},
    {'namespace': 'dash_mantine_components',
     'props': {'checked': True,
               'id': {'index': 1, 'type': 'checkbox'},
               'label': 'My Another to do'},
     'type': 'Input'}, 
    {'namespace': 'dash_mantine_components',
     'props': {'checked': False,
               'id': {'index': 2, 'type': 'checkbox'},
               'label': 'My next level to do'},
     'type': 'Div'}, 
]

cli = MontyList(response)
cli.find({'props.checked': True},{'type':1})

输出:

MontyList([{'type': 'Checkbox'}, {'type': 'Input'}])

与其他 jsonquery 选项相比,我更喜欢这个,因为这个库给人以 MongoDB 相同的感觉。

If you are on python, There is Mini open source version of MongoDB,
MontyDB https://github.com/davidlatwe/montydb
which has over 500+ stars on github, and it is supported by JetBrains.

from montydb.utils import MontyList
response = [
    {'namespace': 'dash_mantine_components',
     'props': {'checked': True,
               'id': {'index': 0, 'type': 'checkbox'},
               'label': 'My first to do'},
     'type': 'Checkbox'},
    {'namespace': 'dash_mantine_components',
     'props': {'checked': True,
               'id': {'index': 1, 'type': 'checkbox'},
               'label': 'My Another to do'},
     'type': 'Input'}, 
    {'namespace': 'dash_mantine_components',
     'props': {'checked': False,
               'id': {'index': 2, 'type': 'checkbox'},
               'label': 'My next level to do'},
     'type': 'Div'}, 
]

cli = MontyList(response)
cli.find({'props.checked': True},{'type':1})

Output:

MontyList([{'type': 'Checkbox'}, {'type': 'Input'}])

I like this over other jsonquery options, as this library gives the same feel of MongoDB.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文