Thursday, December 22, 2016

Javascript-18-JSON to JS Objects




Converting a JSON Text to a JavaScript Object


<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>



Output : Anna Smith

______________________________________________

Note:

comments of the form //… or /*…*/ are not allowed in JSON. This answer is based on:

_______________________________________________

No comments:

Post a Comment