JSON Text to JavaScript Object using eval() Example: JSON Tutorial


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
Advertisements
Try Out Code2care Dev Tools:

Advertisements



#Android #Java #Linux #Microsoft #Google #Python #MacOS #Notepad++ #Microsoft Teams #CSS #PHP #SharePoint #Html #Linux #C-Program #Bootstrap #jQuery #Sublime #Android-Studio #Facebook #Eclipse #WhatsApp #News #MySQL #Json #HowTos #JavaScript #FTP #S3


Advertisements


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency