Parsing json with jQuery

Supplemental 89 views
+2
0 Flares 0 Flares ×

Parsing json data with jQuery is not complicated at all. Here is an efficient example on how to parse json data and append it to your web page.

function parseJson(){
	//Start by calling the json object, I will be using a 
        //file from my own site for the tutorial 
	//Then we declare a callback function to process the data
	$.getJSON('hcj.json',getPosts);

	//The process function, I am going to get the title, 
        //url and excerpt for 5 latest posts
	function getPosts(data){

		//Start a for loop with a limit of 5 
		for(var i = 0; i < 5; i++){
			//Build a template string of 
                        //the post title, url and excerpt
			var strPost = '<h2>' 
				      + data.posts[i].title
				      + '</h2>'
				      + '<p>'
				      + data.posts[i].excerpt
				      + '</p>'
				      + '<a href="'
				      + data.posts[i].url
				      + '" title="Read '
				      + data.posts[i].title
				      + '">Read ></a>';

			//Append the body with the string
			$('body').append(strPost);

		}
	}

}

//Fire off the function in your document ready
$(document).ready(function(){
	parseJson();				   
});
Provided by: Cats who Code
Tagged with:
Posted in jQuery

Discuss:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

No Trackbacks.

Login

Register | Lost your password?
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×