JQuery get data from JSON array

后端 未结 4 1858
半阙折子戏
半阙折子戏 2020-12-15 11:34

This is part of the JSON i get from foursquare.

JSON

tips: {
    count: 2,
    groups: [
    {
        type: \"others\",
        na         


        
相关标签:
4条回答
  • 2020-12-15 11:43

    I think you need something like:

    var text= data.response.venue.tips.groups[0].items[1].text;
    
    0 讨论(0)
  • 2020-12-15 11:47

    You need to iterate both the groups and the items. $.each() takes a collection as first parameter and data.response.venue.tips.groups.items.text tries to point to a string. Both groups and items are arrays.

    Verbose version:

    $.getJSON(url, function (data) {
    
        // Iterate the groups first.
        $.each(data.response.venue.tips.groups, function (index, value) {
    
            // Get the items
            var items = this.items; // Here 'this' points to a 'group' in 'groups'
    
            // Iterate through items.
            $.each(items, function () {
                console.log(this.text); // Here 'this' points to an 'item' in 'items'
            });
        });
    });
    

    Or more simply:

    $.getJSON(url, function (data) {
        $.each(data.response.venue.tips.groups, function (index, value) {
            $.each(this.items, function () {
                console.log(this.text);
            });
        });
    });
    

    In the JSON you specified, the last one would be:

    $.getJSON(url, function (data) {
        // Get the 'items' from the first group.
        var items = data.response.venue.tips.groups[0].items;
    
        // Find the last index and the last item.
        var lastIndex = items.length - 1;
        var lastItem = items[lastIndex];
    
        console.log("User: " + lastItem.user.firstName + " " + lastItem.user.lastName);
        console.log("Date: " + lastItem.createdAt);
        console.log("Text: " + lastItem.text);
    });
    

    This would give you:

    User: Damir P.
    Date: 1314168377
    Text: ajd da vidimo hocu li znati ponoviti

    0 讨论(0)
  • 2020-12-15 11:47

    You're not looping over the items. Try this instead:

    $.getJSON(url, function(data){
        $.each(data.response.venue.tips.groups.items, function (index, value) {
            console.log(this.text);
        });
    });
    
    0 讨论(0)
  • 2020-12-15 11:54

    try this

    $.getJSON(url, function(data){
        $.each(data.response.venue.tips.groups.items, function (index, value) {
            console.log(this.text);
        });
    });
    
    0 讨论(0)
提交回复
热议问题