JSON Parsing

In this post, we are going to discuss about how a JSON string can be parsed before we extract values from them.

As JSON is widely used in almost all web applications, we need to know the better way of parsing it to avail the benefit of using it.

JSON string can be parsed using following JavaScript functions:

  1. eval()
  2. parse()



Using eval()

The eval() function can be used to convert the well formed JavaScript Object Notation(JSON) string into an object.

Invoke eval() to convert JSON string to object

var contact= eval(“(“+'{“firstname”:”Kumar”,”surname”:”Ankit”,”phone”:[“999-9999-909″,”999-9999-999″]}’+”)”);

Don’t forget to embed JSON string with function brackets “(” and “)”.

Get values using JSON object

alert(“Hello ” + contact.firstname + “, we will contact you at ” + contact.phone[0] + “or” + contact.phone[1]);


Using parse()

The eval() function can also be used to convert the well formed JavaScript Object Notation(JSON) string into an object.

Invoke parse() to convert JSON string to object

var contact= JSON.parse(‘{“firstname”:”Kumar”,”surname”:”Ankit”,”phone”:[“999-9999-909″,”999-9999-999”]}’);

Get values using JSON object

alert(“Hello ” + contact.firstname + “, we will contact you at ” + contact.phone[0] + “or” + contact.phone[1]);


eval() Vs parse()

  • JSON.parse() function is not supported by all browsers since the native support for the function is missing in old browsers. Check what are all browsers support JSON.parse() from here.
  • JSON is just a subset of JavaScript. JSON.parse() just parses JSON string present in JavaScript but eval evaluates the full JavaScript language and not just the subset that’s JSON which end up in parsing function calls and other JavaScript code.
  • Time taken for parsing matters: JSON.parse() parses JSON string in quick time when compare to eval(). Check it right from here.

Author: admin

Share This Post On
  • android kikaider

    Quality content is the key to invite the people to pay a quick visit the web
    site, that’s what this web page is providing.

Pin It on Pinterest

Shares