In this session today, we will learn to implement loops in Json.
- So to get started just follow the steps given below :
- First of all create an new folder on the desktop say JSON as shown in the figure :
- Now inside JSON folder create a new file say index.xml .
- Right click on index.xml file and open it with notepad++ ,thus you will have the following look of your window:-
- So lets take an simple example for implementing loop in json.
- In this example we will display the title ,year and genere of the various movies.
- So write the follwing code in notepad++:
<!DOCTYPE html> <html> <head> <title>My Movies</title> <style> h1{text-align:center;} h4{margin:0;padding:5px;background:#f4f4f4;} li{list-style:none;padding-left:5px;} #container{width:600px;margin:auto;overflow:hidden;} </style> <script> var movie1 ={ title:"The Godfather", year:"1972", genre:"Drama", director:"Francis Ford Copolla" } var movie2 ={ title:"Superbad", year:"2007", genre:"Comedy", director:"Greg Mottola" } var movie3 ={ title:"The Departed" , year:"2006", genre:"Drama", director:"Martin Scorsese" } var movie4 ={ title:"Saving Private Ryan" , year:"1998", genre:"Action", director:"Steven Spielberg" } var movie5 ={ title:"The Expendables" , year:"2010", genre:"Action", director:"Sylvester Stallone" } var movies = [ { "title":"The Godfather" , "year":"1972", "genre":"Drama", "director":"Francis Ford Copolla" }, { "title":"Superbad" , "year":"2007", "genre":"Comedy", "director":"Greg Mottola" }, { "title":"The Departed" , "year":"2006", "genre":"Drama", "director":"Martin Scorsese" }, { "title":"Saving Private Ryan" , "year":"1998", "genre":"Action", "director":"Steven Spielberg" }, { "title":"The Expendables" , "year":"2010", "genre":"Action", "director":"Sylvester Stallone" }, ]; </script> </head> <body> <div id="container"> <h1>My Favorite Movies</h1> <ul> <script> //document.write(movie1.title); //document.write(movies[0].title); for(i=0;i < movies.length;i++){ document.write('<h4>'+movies[i].title+'</h4>'); document.write('<li>Year: '+movies[i].year+'</li>'); document.write('<li>Genre: '+movies[i].genre+'</li>'); document.write('<li>Director: '+movies[i].director+'</li>'); } </script> </ul> </div> </body> </html>
- Now after writing the code you will have the following look of your notepad++ window :-
- Hence ,now when you run your file on Google Chrome you will have the following output:-
- Thus we have successfully implemented loops in json using a simple example .