Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON response using jQuery

I'm dealing with a JSON Response in one of my applications. I have established a connection using jsonp successfully. But I'm not able to parse my response.

Code:

<script type='text/javascript'>
(function($) {
var url = 'http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json';

$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'callback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
       console.log(json.topics);
       $("#nav").html('<a href="">'+json.topics+"</a>");
    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);
</script>

Output i'm getting:

[object Object],[object Object],[object Object]

Response Example:

callback({"topics":[{"name":"topic","content":[{"link_text":"link","link_src":"http://www.foodnetwork.com/"},{"link_text":"link","link_src":"http://www.hgtv.com/"},{"link_text":"link","link_src":"http://www.diynetwork.com/"},{"link_text":"link","link_src":"http://www.cookingchanel.com/"},{"link_text":"link","link_src":"http://www.travelchannel.com/"},{"link_text":"link","link_src":"http://www.food.com/"}]},{"name":"topic2","content":[{"link_text":"link","link_src":"http://www.google.com/"},{"link_text":"link","link_src":"http://www.yahoo.com/"},{"link_text":"link","link_src":"http://www.aol.com/"},{"link_text":"link","link_src":"http://www.msn.com/"},{"link_text":"link","link_src":"http://www.facebook.com/"},{"link_text":"link","link_src":"http://www.twitter.com/"}]},{"name":"topic3","content":[{"link_text":"link","link_src":"http://www.a.com/"},{"link_text":"link","link_src":"http://www.b.com/"},{"link_text":"link","link_src":"http://www.c.com/"},{"link_text":"link","link_src":"http://www.d.com/"},{"link_text":"link","link_src":"http://www.e.com/"},{"link_text":"link","link_src":"http://www.f.com/"}]}]});

I want in the form of :

Topic: Link

like image 747
Radhakrishna Rayidi Avatar asked Jun 28 '13 11:06

Radhakrishna Rayidi


2 Answers

Give this a try:

success: function(json) {
   console.log(JSON.stringify(json.topics));
   $.each(json.topics, function(idx, topic){
     $("#nav").html('<a href="' + topic.link_src + '">' + topic.link_text + "</a>");
   });
},
like image 87
Aguardientico Avatar answered Oct 02 '22 16:10

Aguardientico


I was hanging out on Google, then I found your question and it's very simple to parse JSON response into normal HTML. Just use this little JavaScript code:

<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

<script>

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;

</script>

</body>
</html>
like image 22
Justin Imran Avatar answered Oct 02 '22 16:10

Justin Imran