How to parse JSON with jQuery

With jQuery you could easily parse a JSON (which is an object in JavaScript Object Notation). The method parseJSON of jQuery translates the JSON even into the corresponding JavaScript data types. As an example I have chosen the following JSON:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
        "firstName": "Joe",
        "lastName" : "Black",
        "age"      : 28,
        "address"  :
        {
          "streetAddress": "1st Street",
          "city"         : "New York",
          "state"        : "NY",
          "postalCode"   : "10021"
        },
        "phoneNumber":
        [
          {
            "type"  : "home",
            "number": "212555-1234"
          },
          {
            "type"  : "fax",
            "number": "646555-4567"
          }
        ],
        "married" : true,
        "developer" : true	
}

This JSON contains nested objects like address, an array like phoneNumber and key-value pairs of different types like firstName (string), age (number) and married (boolean).

Here it is shown how it is parsed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script src="./js/jquery-1.7.min.js"></script>
<script type="text/javascript">
  var json = '{"firstName":"Joe","lastName":"Black","age":28,"address":{"streetAddress":"1st Street","city":"New York","state":"NY","postalCode":"10021"},"phoneNumber":[{"type":"home","number":"212555-1234"},{"type":"fax","number":"646555-4567"}],"married":true,"developer":false}';
  var object = jQuery.parseJSON(json);
  var firstName = object.firstName; // Joe
  var age = object.age; // 28
  var streetAddress  = object.address.streetAddress;
  var numberOfPhoneNumbers = object.phoneNumber.length; // 2
  var homeNumber = object.phoneNumber[0].number; // 212555-1234
  var faxNumber = object.phoneNumber[1].number; // 646555-4567
  var married = object.married; // true
 
  if(married == true)
    alert('He is a lucky one!'); // ...and he is ;)
 
  // Checking data types
  alert(typeof(firstName)); // string
  alert(typeof(age)); // number
  alert(typeof(married)); // boolean
</script>

Update: Some modern browsers do have native JSON support now. One should therefore look first if native support is available. If not, then use jQuery. You can do this with this code:

var object = JSON && JSON.parse(json) || jQuery.parseJSON(json);

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.