HTML 5 TutorialsLooping through JSON

Looping through JSON

We have gone through the theory of JSON in the previous session. Today we will learn how to create JSON objects and arrays practically and how to traverse through the arrays using loops.
Let’s start the task step by step.

  1. Create a new folder on desktop and name it as “Sec4_Ch21”.
  2. Open a new notepad++ document and save it as “index.html” in the newly created folder “Sec4_Ch21”.
  3. Write the following code in “index.html” file.
  4. <!DOCTYPE html>
    <html>
    <head>
    <title>My Movies</title>
    </head>
    <body>
    </body>
    </html>
    

    When we open the file “index.html” with any browser say chrome, it will look like this:

    initial_output
    fig 1

  5. In this tutorial of Looping through JSON, we are going to use the same information of movies used in XML file in last session but in JSON format. To store information JSON objects are used, so create a JSON object in the head section of the document in the tags as follows:
  6. <head>
    <title>My Movies</title>
    <script>
    var movie={
    	title:"The Godfather",
    	year:"1972",
    	genre:"Drama",
    	director:"Francis Ford Capolla"
    }
    </script>
    </head>
    
  7. In the above code, movie is the object name that contains the information about a movie. Information of an object is always written in the curly braces and it is in the form of name/value pair separated by comma (,).
  8. Now to grab this information and display it on the screen, write the following code in the body section of the document inside
    <script>---</script>

    tags.

  9. <script>
    	document.write(movie.title+’<br><br>’);
    	document.write(movie.genre);
    </script>
    
    • Here, title of the movie is displayed with the statement
      document.write(movie.title+’<br><br>’); 

      where, movie is the object name and title is its property. And genre of the movie is displayed with the statement

      document.write(movie.genre); 

      where, movie is the object name and genre is its property.

    • br tag is used for a line brake.
    • Hence any information in the object is displayed with object name with its property along with a period (.) in between.
    • The statement
      document.write();

      is used to display any text.

    • Output of the above code is shown below:
    • displaying_JSON_object_info
      fig 2

    • The Godfather is the title of the movie and Drama is its genre.
      This is how we access a JSON object.
  10. If we want some more objects i.e. if we want to store the information of some more movies we can create that many objects but it is not a good practice. To store information in more than two or three objects we can directly declare an array.
    • Let us create an array to store the information of five movies.
    • Write the following code in the head section of the document in
      <script>---</script>

      tags:

    • <script>
      var movies =[
      	{
      		title:"The Godfather",
      		year:"1972",
      		genre:"Drama",
      		director:"Francis Ford Capolla"
      	},
      	{
      		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>
      
    • Here, we have stored information of 5 movies in the array named movies.
    • Each array value in the above case is a movie object separated by comma.
    • The objects in the array are contained in the opening and closing square brackets [].
  11. Now let us print some of the array values. Write the following code in body section inside the
    <script>--</script>

    tags.

  12. <script>
    document.write(movies[0].genre+'<br><br>');
    document.write(movies[2].title);
    </script>
    
    • Here, we have printed the values using document.write(); statement.
    • Looking at the statements we can understand that we are trying to print the genre of first movie and the title of the third movie.
    • Since we are dealing with arrays, we know that data is stored in array from index 0 (zero).
    • So while printing the value, the array name with the index of the object in square brackets followed by a particular property with a period in between is given.
    • The output of the code above is shown below:
    • displaying_JSON_array_info
      fig 3

    • In the above output, the genre of first movie and the title of the third movie are displayed.
  13. We have displayed just two values in the above code, but if we want to display the whole array, we cannot just sit and write code for each and every value. We can use any looping structure for this.
    • Let us write the following code to display the whole array using for loop in the body section:
    • <div id="container">
      <h1>My Favourite Movies</h1>
         <ul>
         <script>	
                for(i=0;i<movies.length;i++)	
       	  {
      	    document.write('<h4>'+movies[i].title +'</h4>');
       	    document.write('<li>'+movies[i].year +'</li>');
      	    document.write('<li>'+movies[i].genre +'</li>');
      	    document.write('<li>'+movies[i].director +'</li>');
                }
         </script>
         </ul>	
      </div>
      
    • In the above code, the code to display array values is written in a div block given an id container.
    • A heading My favourite Movies is given in h1 tag.
    • The movies details are displayed in an un-ordered list.
    • <script>--</script>

      tag is defined inside

      <ul>--</ul>

      tags because everything before it, was html and now we want to write the scripting code.

    • So we have used for loop to display the array elements.
    • Condition given in for loop is
      i<movies.length

      . Here we know “movies” is an array and array is an object. Objects have properties and hence length is the property of an array which gives the number of elements present in the array. In the above example of movies, length property will return value 5, since we have 5 movie objects in the array movies and for loop will therefore iterate 5 times.

    • We are going to display the movie details in an un-ordered list with all the movie titles as the heading and the other details of the movie under it as the list items.
    • Title of every movie is displayed with the h4 heading tag in the statement
      document.write('<h4>'+movies[i].title +'</h4>');

      Here, h4 tag is the html part hence written in the string format and concatenated with the code to display movie title i.e. movies[i].title. The variable i will change accordingly from 0 to 5.

    • The output after displaying only movie titles is shown below:
    • displaying_movie_titles_in_for_loop
      fig 4

    • Now, when we write the further statements in the for loop i.e.
      document.write('<li>'+movies[i].year +'</li>');
      document.write('<li>'+movies[i].genre +'</li>');
      document.write('<li>'+movies[i].director +'</li>');

      It will display the year, genre and director under the title of each movie. Since these are the list items of un-ordered list, they are enclosed in the li tags.

    • The output after writing the whole code is seen like this:
    • displaying_movie_details_in_for_loop
      fig 5

    • All the 5 movie details are shown in an un-ordered list in the above output. But this displayed information needs some styling to look presentable.
  14. Let us provide some styling to the page.
    • We have defined a div block with id container in the above given code; this will be used for styling.
    • Write the following code in head section of the page below the page title and outside the script tag:
    • <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>
      
    • The page after styling will look like this:
    • Array_elements_after_styling
      fig 6

    • Let us understand, how styling is done?
    • We have used inline styling by writing the code for it in the
      <style>---</style>

      tags in the head section.

    • First the Heading “My Favourite Movies” heading is styled. Since this heading is written in
      <h1>--</h1>

      tags, h1 tag is styled. The code for it is shown below:

    • h1{
      		text-align:center;
            }
      
    • Here, Due to h1 tag the size of the heading is already large, so we have just placed the heading text at the center of the page by using the statement text-align:center;
    • Next, we have styled the h4 tag that contains the titles of the movies. The code is shown below:
    • h4{
      		margin:0;
      		padding:5px;
      		background:#f4f4f4;
             }
      
    • Here, each movie title is given no margin i.e. margin:0; padding of 5 pixels is given from all sides and a grey background color is given using the statement background:#f4f4f4;
    • Next the list items i.e. the movie details are styled using the following code:
    • li{
      		list-style:none;
      		padding-left:5px;
        }
      
    • The list items have bullets due un-ordered list, these bullets are removed using the statement list-style:none; padding of 5 pixels is given from the left side using statement padding-left:5px;
    • The div block having the id container is also styled with the following code:
    • #container{
      		width:600px;
      		margin:auto;
      		overflow:hidden;
      	}
    • Since container is an id of the div block, it is preceded with the # sign. The div block is given a width of 600 pixels. Margin is given auto; this auto indicates that all the content should be placed in the middle of the page. Any overflow or distortion is hidden using the statement overflow:hidden;

Thus we successfully finished working with Looping through JSON.

Previous articleXML with DTD Schema
Next articleAJAX Fundamentals

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -