Saturday, August 24, 2013

How to Read and Parse JSON using jQuery

In this short post, you will find how you to parse the JSON string using jQuery. JSON (JavaScript Object Notation) is an data exchange format and which is human-readable data. jQuery provides a metohd called "parseJSON" which takes a well-formed JSON string and returns the resulting JavaScript object.

Related Post:
  • Read and Process XML using jQuery Ajax
  • jQuery- Parse XML and HTML

Some facts about JSON

  • JSON is limited to text and numeric values.
  • It doesn't support binary data.
  • An JSON object is a set of key / name pairs which starts with "{" and ends with "}".
Below is sample jQuery code which parses JSON string using parseJSON method which returns an object.
1$(document).ready(function() {
2  var jsonp = '[{"Lang":"jQuery","ID":"1"},{"Lang":"C#","ID":"2"}]';
3  var lang = '';
4  var obj = $.parseJSON(jsonp);
5  $.each(obj, function() {
6      lang += this['Lang'] + "<br/>";
7  });
8  $('span').html(lang);
9});​
See result below.