In a real world scenario JSON data is received as HTTPRequest from a web server, this data has to be converted into JavaScript Object in order to be displayed on a web page.
JavaScript eval() function is used to convert JSON text into JSON Object.
The JavaScript Compiler parses JSON text to JavaScript object.
Note that the text must be surrounded by braces to avoid errors.
Nested JSON Object :<html>
<head>
<script type="text/javascript">
function jsonEvalEx() {
//JSON Text
var mySongs = '{"songs":[' +
'{"songName":"Imagine","songArtist":"John Lennon" },' +
'{"songName":"Voodoo Child","songArtist":"Jimi Hendrix" },' +
'{"songName":"Kashmir","songArtist":"Led Zeppelin" }]}';
var javaScriptObj = eval ("(" + mySongs + ")");
var data = "";
data = data + "Song : " + javaScriptObj.songs[0].songName + "<br>";
data = data + "Artist : " + javaScriptObj.songs[0].songArtist + "<br><br>";
data = data + "Song : " + javaScriptObj.songs[1].songName + "<br>";
data = data + "Artist : " + javaScriptObj.songs[1].songArtist + "<br><br>";
data = data + "Song : " + javaScriptObj.songs[2].songName + "<br>";
data = data + "Artist : " + javaScriptObj.songs[2].songArtist + "<br><br>";
document.getElementById("mySongs").innerHTML = data;
}
</script>
</head>
<body onload="jsonEvalEx();">
<div id="mySongs"></div>
</body>
</html>
Output:
Song : Imagine
Artist : John Lennon
Song : Voodoo Child
Artist : Jimi Hendrix
Song : Kashmir
Artist : Led Zeppelin
More Posts related to Json-Tutorial,
- JSON Text to JavaScript Object using eval() Example: JSON Tutorial
- JSON Tutorial: List of Lessons
- JSON Schema and Hyper-Schema : JSON Tutorial
- JSON with PHP Example: JSON Tutorial
- JSON Nest Objects Example: JSON Tutorial
- JSON Schema Validator Libraries: JSON Tutorial
- JSON Syntax : JSON Tutorial
- JSON Datatypes : Tutorial
More Posts:
- How to Access Terminal (Command Line) in Eclipse IDE - Eclipse
- MacBook - Time Limit - You have reached your time limit, Ignore Limit - MacOS
- C#.Net error The underlying connection was closed: An unexpected error occurred on a send - SharePoint
- How to make Text in TextView bold and italic in Android - Android
- connection.url property value in hibernate.cfg.xml for mysql - Java
- Word count in Notepad++ - NotepadPlusPlus
- Share Image and Text on Instagram from Android App using Share Dialog - Android
- Calculate Area of ellipse - C-Program