LINQ was a major advancement in programming. Traditionally when you wanted to find a few items in a object collection you would write a loop and inspect the properties of each object and then return the items that matched. This was cumbersome and often resulted in the developer writing a lot of functions to return objects based on different types of searches. LINQ solved this problem completely because now you can use a SQL like syntax to return objects from a collection. LINQ comes in many different flavors, there is LINQ to SQL, LINQ to XML and LINQ to entities. However, today I ran across a project called jLinq, which is LINQ for JSON!.
JSON stands for JavaScript Object Notation. JSON is simply a way to serialize object(s) to a string so they can be marshaled and eventually consumed by the client. For example here is the JSON string representing a Person:
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
],
"newSubscription": false,
"companyName": null
}
So what could you use JLinq for? Well, my first idea was to use it on a data grid. Most of the time, when I build a data grid in a web app I will give the user the ability to filter and sort the data. If I return a JSON string to the browser which represented a bunch of people then I could take that data and dynamically build a grid (html table) using jQuery. Additionally, I could add a search box to the top of grid which would let the user specify search criteria. When they hit the search button the data would be filtered and the grid would be modified to show the matching records. Using jQuery and jLinq I could easily filter down the data to display on the matching rows without making any roundtrips to the server. Here is a sample jLinq query taken directly from the project website:
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
If you have written any LINQ code before you can see the familiarities in the jLinq query above. Better yet, if you want to test drive jLinq then you can head to the project website and start writing queries using the online demo page.
Finally, In order to start using the library in your web app you just need to download the 16KB script file and add it as an include on your html page. I would highly recommend checking this project out. The author, Hugo J. Bonacci III did a fantastic job on the project and I really appreciate the fact that he made his code available to all of us. Thanks Hugo!