开发者

What libraries are available to manipulate JSON data in JavaScript

I have a webpage that uses JavaScript to retrieve JSON from a web service. The JSON could contain 10 records or 100 records. On the webpage, I want to provide a flexible interface that would allows the user to filter and order the data. The filtering/ordering data should be processed in the browser. I do not want the web service to do the filtering, because a round trip to the server would be need for each action and this seems very inefficient.

I have experience with JQuer开发者_开发知识库y, but the solution does not need to depend of JQuery.

Many of the options I like pertain to LINQ in JavaScript. Below is a list of JavaScript libraries that are based on LINQ; I also added the date the library was last updated. Is there a standard that the industry is using?

  • linq.js - LINQ for JavaScript (Jan, 21, 2011)
  • JSINQ - LINQ to Objects for JavaScript (Apr, 4 2010)
  • LINQ to JavaScript (Jun, 16 2009)

Whichever library is decided on, it needs cross browser supported.

I’m not requiring that the library must be compatible with JQuery, or require that it must use LINQ’s syntax. But I do like JQuery and the flexibility that LINQ provides.


The important point is that JSON data is simply a JavaScript object so you can use any library that allows you to manipulate objects.

I would recommend underscore.js as a general utility belt for these kind of issues.

This way we can manipulate data easily

var jsonData = $.getJSON(url);

var filtered = _.filter(jsonData, function(val, key) {
    if (val > 10) return true;
});

var sorted = _.sortBy(jsonData, function(val, key) {
    return order(val);
});

Filtering and ordering relies on your data model. I recommend you use some kind of wrapper to represent your data model on the client.

var MyModel = function(json) {
    var data = json;

    this.filterBySize = function(size) {
        data = _.filter(data, function(val) {
            return val > size
        });
    };

    ...
}

var model = new MyModel(json);
model.filterBySize(10);

An alternative is to use a large library like backbone.js and creating a Backbone.Model for your record and a Backbone.Collection for your entire data set. Then you can simply call .sort, .sortBy, .filter on your Collection.

If your going to bring backbone out then your moving towards clientside MVC and you can use the entire toolset to connect your data and your UI together nicely. Just overwrite Backbone.sync with your own server communication.


Check this linq library just published yesterday and it's very powerful

https://github.com/iabdelkareem/LINQ-To-JavaScript

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜