JSON's main use is to fetch JSON data from a web server and convert JSON data to JavaScript object for use on the web page.
JSON Example:
var data = '{ "book" : [' +
'{ "language":"PHP" , "author":"Rasmus Lerdorf" },' +
'{ "language":"C" , "author":"Dennis Ritchie" },' +
'{ "language":"Java" , "author":"James Gosling" } ]}';
We can use the JavaScript eval() function to convert a JSON text into a JavaScript object.
var obj = eval ("(" + data + ")");
JSON and JavaScript Example:
Language: <span id="lang0"></span><br>
Author: <span id="auth0"></span><br>
Language: <span id="lang1"></span><br>
Author: <span id="auth1"></span><br>
<script>
var data = '{ "book" : [' +
'{ "language":"PHP" , "author":"Rasmus Lerdorf" },' +
'{ "language":"C" , "author":"Dennis Ritchie" },' +
'{ "language":"Java" , "author":"James Gosling" } ]}';
var obj = eval ("(" + data + ")");
document.getElementById("lang0").innerHTML = obj.book[0].language
document.getElementById("auth0").innerHTML = obj.book[0].author
document.getElementById("lang1").innerHTML = obj.book[1].language
document.getElementById("auth1").innerHTML = obj.book[1].author
</script>
The output of the Program:
Language: PHP Author: Rasmus Lerdorf Language: C Author: Dennis Ritchie
eval() function can be used to execute any JavaScript; this represents a potential security problem.
JSON parser is used to convert a JSON text to a JavaScript object, JSON parser only recognize JSON text, and the script does not compile.
JSON Parser Example:
obj = JSON.parse(data);