how to parse Json in javascript?

0 votes
221 views
asked Aug 15, 2014 in java script by haum
recategorized Aug 15, 2014 by admin

Hi

   how to parse Json in javascript? How to parse the follwoing content in java scripe

{
  "employees": [
    {
      "firstName": "John",
      "lastName": "Doe"
    },
    {
      "firstName": "Anna",
      "lastName": "Smith"
    },
    {
      "firstName": "Peter",
      "lastName": "Jones"
    }
  ]
}

1 Answer

0 votes
answered Aug 15, 2014 by admin (8,115 points)

Hi check this code

 

  <!DOCTYPE html>

<html>
<body>
 
<h2>Create Object from JSON String</h2>
 
<p id="demo"></p>
 
<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
 
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
 
</body>
</html>
...