是否有(大致)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),但它似乎还没有一个标准的用法或库集出现。虽然单独实现每个功能都是相当琐碎的,但如果有人已经做对了,我就不想重新发明轮子。

有什么建议吗?

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..)


当前回答

我使用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 

其他回答

据我所知,SpahQL是其中最有前途、考虑最周全的一种。我强烈建议大家去看看。

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

它既是一种完全用JSON编写的jsql语言,也是一种参考实现。你可以说,“我想在数组中找到所有对象,其name==="John" && age===25 as:

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

参考实现searchjs可以在浏览器中工作,也可以作为节点npm包工作

npm install searchjs

它还可以做复杂连接和否定(NOT)之类的事情。它本身就忽略了大小写。

它还没有做求和或计数,但在外面做这些可能更容易。

你可以使用linq.js。

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

var data = [{x: 2, y: 0}, {x: 3 y: 1}, {x: 4, y: 1}); // sum (x) where y > 0 -> console.log (Enumerable.From(数据)其中(" $。y > 0").Sum("$.x")); // list (x) where y > 0 -> [3,4] console.log (Enumerable.From(数据)其中(" $。y > 0").Select("$.x").ToArray()); < script src = " https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js " > < /脚本>

PythonQL提供了一种嵌入式语法,IMHO是对SQL的改进,主要是因为group、window、where、let等可以自由混合。

$ 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

你也可以使用Underscore.js,它基本上是一个瑞士刀库来操作集合。使用_。过滤器,_。勇气,_。减少你可以做类似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

js可以在客户端和服务器端工作,是一个著名的库。

你也可以使用Lo-Dash,它是Underscore.js的一个分支,性能更好。