如何在JSON上应用复杂的数据过滤器,比如SQL where子句



我使用Json来表示客户端(javascript)的数据,我将。net数据表对象转换为Json,现在需要对Json数据应用过滤器。我用_。在哪里应用基本的数据过滤器,但需要复杂的过滤,如:

where = (stundentID = 55 and school='abc') AND (City='xyz' or City ='abc')

是我们在Oracle或sql server查询中使用的一种基本过滤类型。现在,我如何使用underscore.js或类似Json或javascript结构的东西来应用这种机制。我可能还需要做查询获得Top N记录,使用聚合[Sum(sales)==500]在javascript。等待您宝贵的建议。

谢谢,

假设您将这个JSON表示为常规JavaScript对象(毕竟没有JSON对象这种东西),那么最好的选择可能是使用linq.js

你可以这样做:

var studentFilteredArray = 
          Enumerable.From(students)
                    .Where(function(s) { return s.studenId == 55;  })
                    .OrderBy(function(s) { return s.LastName; })
                    .ToArray();

或者从上面的例子中:

.Where(function(s) { 
      return s.studentID === 55 && s.school === 'abc' && (s.City === 'xyz' || s.City === 'abc') 
});

你也可以尝试alasql.js,在那里你可以使用标准的SQL SELECT where语句。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')"));

最新更新