NovoGeek's Blog (Archive)

Technical insights of a web geek

Filtering .NET 3.5 returned JSON with jQuery

In .NET 3.5, when a Web service class is decorated with “ScriptService” attribute, the web service returns data in JSON format [MSDN]. I have demonstrated this with a simple example in the article, Passing JSON objects in .NET 3.5.

Let us consider that our “person” class has several properties, of which only few are useful on the client side for data binding. We can filter this object in two ways:

1. On the server side:- Create a dictionary object [System.Collections.Generic.Dictionary(Of TKey, TValue)], add the desired properties to dictionary object and return it.

2. On the client side:- In cases where a quick filter has to be done without touching server side code, we can use jQuery’s each function to create a custom JSON object.

Suppose you want to filter only “country” and “code” out of the below JSON data,

var players = 
[{ "country": "India", "code": "Ind", "name": "Sachin" },
{ "country": "Sri Lanka", "code": "SL", "name": "Murali" },
{ "country": "Australia", "code": "Aus", "name": "Shane" },
{ "country": "West Indies", "code": "WI", "name": "Lara"}];

you can simply write the below jQuery code:

var newObject = {}; //Creating a new object
$.each(players, function() { //Looping through our players array using jQuery's each function
    newObject[this.country] = this.code; //Creating our custom "name/value" pair
});

So, our newObject will contain new data(having only “country” and “code”). If you want to access country code, you can simply say “newObject.India”, which gives “Ind”.

This tip is particularly useful in cases like filling dropdown lists with JSON data. By default, the server’s JSON data contains several properties which are not required. In such cases, this client side filter comes as a handy tip :)

Pingbacks and trackbacks (2)+

Comments are closed