Parsing a message in JavaScript with JSON

In the previous section of example we have studied how to create message in JSON in JavaScript and now we will come to know that how we can parse the message in JSON in JavaScript.

Parsing a message in JavaScript with JSON

Parsing a message in JavaScript with JSON

     

In the previous section of example we have studied how to create message in JSON in JavaScript and now we will come to know that how we can parse the message in JSON in JavaScript.

We can parse the message with JSON in JavaScript by using the method "String.parseJSON(filter)". It parses the JSON message to an string or object. The parameter "filter" is optional in this method which is used to filter message or transform their results. This method internally uses the JavaScript's method eval() to parse messages.

Here is the full example code for ParseMessageJSON.htm as follows:

 

 

ParseMessageJSON.htm

<html>
<head>
<title>Parsing Message using JSON in JavaScript</title>
<script language="javascript" src="json2.js"></script>
<script language="javascript" >
var students = {
   
"Maths" 
  "Name"  "Amit",  // First element
  "Marks" 67,
  "age" 23 },  
  {
   "Name"   "Sandeep",  // Second element
  "Marks" 65,
  "age" 21 }
 
 
// Printing Maths array values in the alert message
var i=0
var arrayObject = new Array();
for(i=0;i<students.Maths.length;i++)
{  
  arrayObject.push(students.Maths[i].Name);
  arrayObject.push(students.Maths[i].Marks);
  arrayObject.push(students.Maths[i].age);
}  
  alert("Parsing JSON Message Example ");
  alert(arrayObject.toJSONString().parseJSON());
</script>
</head>
<body>
 Parsing Message using JSON in JavaScript
</body>
</html>

To run this example we need to have json2.js file included with our ParseMessageJSON.htm file. File "json2.js" is as same as in our previous example of "creating message in JavaScript with JSON" .

Output:

Run ParseMessageJSON.htm file on your browser. It will generate output on your browser as follows:




Download Code