简体   繁体   中英

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. I used _.where to apply basic data filter , but need complex filtering like:

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. Now how can i apply such mechanism using underscore.js or some thing equivelant on Json or javascript structures. I might also need to do query of getting Top N record , using aggregation [ Sum(sales)==500] at javascript. 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

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 was specially designed to work with JSON arrays like tables in database.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM