Tuesday, March 8, 2016

JavaScript and JSON

If we have a JSON string like this:

{"result":{"information":[{"name":"Tom","age":25},{"name":"Andy","age":30},{"name":"Peter","age":35},{"name":"David","age":40}]}}

How do we use it in JavaScript?

The answer is very easy. Just use JSON.parse().

JavaScript code:


<script language="JavaScript">
<!--

var JSONStr ='{"result":{"information":[{"name":"Tom","age":25},{"name":"Andy","age":30},{"name":"Peter","age":35},{"name":"David","age":40}]}}';
var JSONObj = JSON.parse(JSONStr);

var count;
for (count = 0 ; count <=3 ; count++){
    document.write("<br><br>");
    document.write(JSONObj.result.information[count].name+" ");
    document.write(JSONObj.result.information[count].age);
}
</script><noscript>
Your browser doesn't support JavaScript.
</noscript>

Result:


Related Information:

Simple JavaScript code - Hello World and Current Time
iOS: Print out JSON content in Swift playground

No comments:

Post a Comment