访问JSON数据 - 未定义

时间:2016-11-06 09:40:39

标签: javascript json

我有这个json:

{
"total": 1,
"per_page": "10",
"current_page": 1,
"last_page": 1,
"next_page_url": null,
"prev_page_url": null,
"from": 1,
"to": 1,
"data": [
    {
        "id": 2,
        "name": "Artista di prova",
        "artist_hash": "Gqrrx6NrtqqMpvEN",
        "spotify_followers": null,
        "spotify_popularity": 66,
        "image_small": null,
        "image_large": null,
        "fully_scraped": 0,
        "updated_at": "2016-11-06 08:21:02",
        "bio": "",
        "wiki_image_large": null,
        "wiki_image_small": null,
        "tracks": [
            {
                "id": 1,
                "name": "Traccia di prova",
                "album_name": "Album di prova",
                "number": 1,
                "duration": 18133,
                "artists": [
                    "Artista di prova"
                ],
                "youtube_id": null,
                "spotify_popularity": 50,
                "album_id": 1,
                "temp_id": null,
                "url": "http://myapp.app/track/1/mov/stream",
                "artist_id": 2
            },
            {
                "id": 3,
                "name": "Traccia di prova 2",
                "album_name": "Album di prova",
                "number": 1,
                "duration": 18133,
                "artists": [
                    "Artista di prova"
                ],
                "youtube_id": null,
                "spotify_popularity": 50,
                "album_id": 1,
                "temp_id": null,
                "url": "http://myapp.app/track/1/mov/stream",
                "artist_id": 2
            }
        ]
    }
]

}

我需要访问tracks字段并获取所有数据 我尝试过:

$http.get('artist', {params:params}).success(function(response) {
            $scope.items = response.data;
            $scope.tracks = response.data.tracks;

            console.log($scope.tracks);


        })
    };

但我得undefined

如何访问tracks字段?

2 个答案:

答案 0 :(得分:1)

响应的

data属性是一个数组,因此您需要通过索引访问它:

response.data[0].tracks;

答案 1 :(得分:0)

请记住,tracks是一个对象数组,并且还要记住它位于data键下,该键也是一个数组。天真的方式是使用各自的索引获取每个数据,如下: response.data[0].tracks[anotherIndex]获取数组中的一个对象,response.data[0].tracks来记录数组。 但在实际情况中,您可能需要正确地遍历datatracks并在组件上呈现它们的值。