how to get json data in jquery

12,999

Solution 1

Here is a working example, just replace with your app id:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Loop</title>
<style>
ul {list-style: none;}
</style>
</head>
<body>
<div id="content"></div>
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
   FB.init({
    appId  : 'APP_ID',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml  : true, // parse XFBML
    oauth  : true // enable OAuth 2.0
  });
    FB.login(function(response) {
        if (response.authResponse) {
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me/posts', { limit: 3 }, function(d) {
              if(!d.data.length) return;
                var html = "";
                $.each(d.data, function(idx, post) {
                    html += "<div class='container'>";
                    html += "<ul>";
                    html += "<li>Name: "+ post.from.name +"</li>";
                    if(post.message) html += "<li class='message'>Message: " + post.message + "</li>";
                    if(post.comments) {
                        if( post.comments.count > 1)
                            html += "<li>There are " + post.comments.count + " comments</li>";
                        else
                            html += "<li>There is one comment</li>";
                        html += "<li><ul>";
                        $.each(post.comments.data, function(i, comment) {
                            html += "<li class=''>" + comment.message + "</li>";
                        });
                        html += "</ul></li>";
                    }
                    html += "</ul>";
                    html += "</div>";
                });
                $('#content').html(html);
            });
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, {scope: 'read_stream'});


  };
  (function(d){
     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     d.getElementsByTagName('head')[0].appendChild(js);
   }(document));
</script>
</body>
</html>

Your code is fine you only have one typo in the comments loop:

$.each(res.commments.data, function(i, comment) {

If you know the structure of the response, which is the case, you don't need to use the first $.each:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Loop</title>
</head>
<body>
<script>
$(document).ready(function() {
    $.getJSON('json.php', function(d) {
        if(!d.data[0]) return;
        var html = "";
        var result = d.data[0];
        html += "<div class='container'>";
        html += "<ul>";
        html += "<li>"+ result.from.name +"</li>";
        html += "<li class='message'>" + result.message + "</li>";
        if(result.comments) {
            html += "<li>Comments: " + result.comments.count + "</li>";
            $.each(result.comments.data, function(i, comment) {
                html += "<li class=''>" + comment.message + "</li>";
            });
        }
        html += "</ul>";
        html += "</div>";
        $('body').html(html);
    });
});
</script>
</body>
</html>

json.php:

<?php
$var = <<<EOD
{
"data":
[
    {
        "id":"123",
        "from":{"name":"name","id":"12"},
        "message":"Message",
        "comments": {
                        "data":
                        [
                            {
                                "id":"342",
                                "from":{"name":"name","id":"32"},
                                "message":"comment message 1"
                            },
                            {
                                "id":"341",
                                "from":{"name":"name","id":"21"},
                                "message":"comment message 2"
                            }
                        ],
                        "count":2
                    }
    }
]

}
EOD;
echo $var;
?>

Solution 2

That's because you're iterating comments.data already!

What's the deal? Your d is a normal JS object (an array in this case), so you can do

function (d) { alert(d[0].comments.data);}

or

function (d) {
    $.each(d, function (i, res) {
        alert(res.comments.data);
    });
}
Share:
12,999
doforumda
Author by

doforumda

Updated on June 04, 2022

Comments

  • doforumda
    doforumda about 2 years

    How can I get the comments from below json data?

    {
    "data":
    [
        {
            "id":"123",
            "from":{"name":"name","id":"12"},
            "message":"Message",
            "comments": {
                            "data":
                            [
                                {
                                    "id":"342",
                                    "from":{"name":"name","id":"32"},
                                    "message":"comment message 1"
                                },
                                {
                                    "id":"341",
                                    "from":{"name":"name","id":"21"},
                                    "message":"comment message 2"
                                }
                            ],
                            "count":2
                        }
        }
    ]
    

    }

    I know how to get id, from and message. but I do not know how can I get data inside comments.

    here is my jquery code

    $.getJSON(newsfeed_url,function(d) {
        $.each(d.data, function(i,res) {
            html += "<div class='container'>";
            html += "<li>"+ res.from.name +"</li>";
            html += "<li class='message'>" + res.message + "</li>";
            html += "<li>Comments: " + res.comments.count + "</li>";
    
            $.each(res.commments.data, function(i, comment) {
                html += "<li class=''>" + comment.message + "</li>";
            });
            html += "</div>";            
        });
        html += "</ul>";
        $("#contents").html(html);
    });
    

    my current code does get res.from.name, res.comments.count but it does not get data inside comments i.e. res.comments.data.

    how can I achieve it?

    here is my actual json file. The above one I gave was example. here it goes

    {
    "data":
    [
        {
        "id":"7234234234_32423432",
        "from":{"name":"name","id":"34534534534"},
        "message":"Näyttelyn puoliväli/kolmas viikko.\n\nhttp://alastonkriitikko.blogspot.com/2011/09/nayttelykuvia-458-459-kadulla-ja.html",
        "picture":"http://external.ak.fbcdn.net/safe_image.php?d=AQAWGCUrr4QBEFXk&w=90&h=90&url=http%3A%2F%2F1.bp.blogspot.com%2F-pBAudI2423s%2FTm7y-ajz62I%2FAAAAAAAAE6g%2F-K4s1sfrYpI%2Fs72-c%2FIMG_1737.JPG",
        "link":"http://alastonkriitikko.blogspot.com/2011/09/nayttelykuvia-458-459-kadulla-ja.html",
        "name":"name: Näyttelykuvia 458 & 459: Kadulla ja studiossa",
        "caption":"alastonkriitikko.blogspot.com",
        "description":"Näyttelykuvia ja kritiikkejä sekä metakritiikkiä, päiväkirjamerkintöjä ja satunnaisia hajahuomioita taiteesta – sekä nähdystä että luetusta",
        "icon":"http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif",
        "actions":
        [
            {"name":"Comment","link":"http://www.facebook.com/23432354/posts/324534543546565"},
            {"name":"Like","link":"http://www.facebook.com/759688182/posts/274846375878348"}
        ],
        "type":"link",
        "created_time":"2011-09-13T09:47:23+0000",
        "updated_time":"2011-09-13T09:58:30+0000",
        "comments":
            {
                "data":
                [
                    {
                        "id":"3242342343_345878348_4012650",
                        "from":{"name":"name","id":"4534544"},
                        "message":"hitto. pitää ehtiä näkemään. Niin pitkä on matka kantsusta keskustaan...",
                        "created_time":"2011-09-13T09:51:29+0000"
                    },
                    {
                        "id":"32453543534_34534534348_4012674",
                        "from":{"name":"name","id":"54654654645"},
                        "message":"Ainakin verraten tähän matkaan Sörkästä keskustampaan, joka usein väittää itseään minulle liian pitkäksi.",
                        "created_time":"2011-09-13T09:58:30+0000"
                    }
                ],
                "count":2
            }
    }
    ]
    }
    

    It is still not working. BTW I am not taking data from facebook or somewhere else. I have local .json file and from there I get data. The object which it says is undefined is "res.comments.data".

    here is my whole code

    $(function() {
    var newsfeed_url = "json_data/newsfeed.json";
    var html = "<ul>";
    $.getJSON(newsfeed_url,function(d) {
        $.each(d.data, function(i,res) {
            var userid = res.from.id;
            var username = res.from.name;
            var msg = res.message;
            var date_time = res.created_time;
            //var like = res.created_time;
            var url = "https://graph.facebook.com/" + userid + "/picture";
            var pUrl = "http://www.facebook.com/profile.php?id=" + userid;
            html += "<div class='container'>";
            html += "<li class='profile_image'><img src='" + url + "' /></li>";
            html += "<li class='from_name'><a href='" + pUrl + "'>" + username + "</a></li>";
            html += "<li class='message'>" + msg + "</li>";
            html += "<li class='time_ago'>" + relative_time(date_time) + "</li>";
            $.each(res.actions, function(i, action) {
                html += "<li class=''><a href='" + action.link + "'>" + action.name + "</a></li>";
                //html += "<li class=''>Link: " + action.link + "</li>";
            });
            html += "<li>Comments: " + res.comments.count + "</li>";
            //html += "<li>Likes: " + res.likes.count + "</li>";
            //html += "<li>Comments: " + res.comments.data + "</li>";
            alert(res.comments.data);
            $.each(res.comments.data, function(j, comment) {
                //alert(comment.message);
                html += "<li class=''>" + comment.message + "</li>";
            });
    
           //alert(res.comments.data);
            html += "<li class='no_float'></li>";
            html += "</div>";
    
    
    
            //newsfeed(userid, username, msg, date_time, like);
        });
        html += "</ul>";
        $("#contents").html(html);
    });
    
    //display message short.
    function short_msg(msg, un) {
        var limit = 80;
        if(un)
            return msg.length > 30 ? msg.substring(0, 30) : msg;
        else 
            return msg.length > limit ? msg.substring(0, limit) + "..." : msg;
    }
    
    //function which displays date and time in readable format
    function relative_time(date_str) {
        if (!date_str) {return;}
        var s = $.trim(date_str);
        s = s.replace(/\.\d\d\d+/,""); // remove milliseconds
        s = s.replace(/-/,"/").replace(/-/,"/");
        s = s.replace(/T/," ").replace(/Z/," UTC");
        s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
        var parsed_date = new Date(s);
        var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); //defines relative to what ..default is now
        var delta = parseInt((relative_to.getTime()-parsed_date)/1000);
        delta=(delta<2)?2:delta;
        var r = "";
        if (delta < 60) r = delta + " seconds ago";
        else if(delta < 120) r = " a minute ago";
        else if(delta < (45*60)) r = (parseInt(delta / 60, 10)).toString() + " minutes ago";
        else if(delta < (2*60*60)) r = " an hour ago";
        else if(delta < (24*60*60)) r = "" + (parseInt(delta / 3600, 10)).toString() + " hours ago";
        else if(delta < (48*60*60)) r = "a day ago";
        else r = (parseInt(delta / 86400, 10)).toString() + " days ago";
    
        return r;
    }
    });