是否有(大致)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..)


当前回答

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

其他回答

如果你使用python, MongoDB有迷你开源版本, MontyDB https://github.com/davidlatwe/montydb 它在github上有500多颗星,并且得到了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相同的感觉。

我推荐我正在做的项目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)
        };
    });

它也是完全可扩展的!

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

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

上面的例子很容易用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/上下载和讨论

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

Var对象= {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(对象,路径));

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

它如何工作的例子(在浏览器这里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

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

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

我希望它对你有用…… 问候