[英]How to apply complex data filters like SQL where clause on JSON
I am Using Json to represent data at client side(javascript), I converted .net datatable object to json and now need to apply filter on Json data. 我正在使用Json在客户端(javascript)表示数据,我将.net datatable对象转换为json,现在需要对Json数据应用过滤器。 I used _.where to apply basic data filter , but need complex filtering like:
我使用_.where来应用基本数据过滤器,但需要像这样的复杂过滤:
where = (stundentID = 55 and school='abc') AND (City='xyz' or City ='abc')
Its a basic type of filtration that we used in Oracle or sql server queries. 它是我们在Oracle或sql服务器查询中使用的基本过滤类型。 Now how can i apply such mechanism using underscore.js or some thing equivelant on Json or javascript structures.
现在,我如何使用underscore.js或Json或javascript结构上的某些东西应用这种机制。 I might also need to do query of getting Top N record , using aggregation [ Sum(sales)==500] at javascript.
我可能还需要使用JavaScript的聚合[Sum(sales)== 500]进行查询以获取前N个记录。 Waiting for your valuable suggestions.
等待您的宝贵建议。
Thanks, 谢谢,
Assuming you have this JSON represented as a regular JavaScript object—there's no such thing as a JSON object, after all—you're best bet would likely be to use linq.js 假设您将此JSON表示为常规JavaScript对象-毕竟没有JSON对象之类的东西-最好是使用linq.js
You'd be able to do things like: 您将可以执行以下操作:
var studentFilteredArray =
Enumerable.From(students)
.Where(function(s) { return s.studenId == 55; })
.OrderBy(function(s) { return s.LastName; })
.ToArray();
Or from your example above: 或从上面的示例中:
.Where(function(s) {
return s.studentID === 55 && s.school === 'abc' && (s.City === 'xyz' || s.City === 'abc')
});
You also can try alasql.js , where you can use standard SQL SELECT WHERE statement. 您也可以尝试使用alasql.js ,在其中可以使用标准的SQL SELECT WHERE语句。 Alasql was specially designed to work with JSON arrays like tables in database.
Alasql专门设计用于处理JSON数组,例如数据库中的表。
// Create database and describe the table
var db = new alasql.Database();
db.exec('CREATE TABLE students ([studentID] INT, school STRING, [City] STRING)');
// Assign you array here
db.tables.students.data = [
{studentID: 55, school: 'abc', City:'abc'},
{studentID: 56, school: 'klm', City:'xyz'},
{studentID: 57, school: 'nyz', City:'xyz'}
];
// Use regular SQL
console.log(db.exec("SELECT * FROM students "
+" WHERE ([studentID] = 55 AND school='abc') AND ([City]='xyz' OR [City] ='abc')"));
Try this example in jsFiddle . 在jsFiddle中尝试此示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.