Posted By

fuelishways on 06/19/14


Tagged

jquery json


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Beppoi


parsing json with jquery


 / Published in: jQuery
 

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.

http://www.catswhocode.com/blog/useful-jquery-code-snippets

  1. function parseJson(){
  2. //Start by calling the json object, I will be using a
  3. //file from my own site for the tutorial
  4. //Then we declare a callback function to process the data
  5. $.getJSON('hcj.json',getPosts);
  6.  
  7. //The process function, I am going to get the title,
  8. //url and excerpt for 5 latest posts
  9. function getPosts(data){
  10.  
  11. //Start a for loop with a limit of 5
  12. for(var i = 0; i < 5; i++){
  13. //Build a template string of
  14. //the post title, url and excerpt
  15. var strPost = '<h2>'
  16. + data.posts[i].title
  17. + '</h2>'
  18. + '<p>'
  19. + data.posts[i].excerpt
  20. + '</p>'
  21. + '<a href="'
  22. + data.posts[i].url
  23. + '" title="Read '
  24. + data.posts[i].title
  25. + '">Read ></a>';
  26.  
  27. //Append the body with the string
  28. $('body').append(strPost);
  29.  
  30. }
  31. }
  32.  
  33. }
  34.  
  35. //Fire off the function in your document ready
  36. $(document).ready(function(){
  37. parseJson();
  38. });

Report this snippet  

You need to login to post a comment.