Python解析JSON嵌套数据

时间:2017-12-24 08:57:51

标签: python json python-3.x parsing

我试图从setlist.fm api解析这个JSON数据。我试图从每个设置列表中按顺序获取所有歌曲名称。我环顾四周,但互联网上描述的方法都没有奏效。

这是JSON数据

    {'itemsPerPage': 20,
 'page': 1,
 'setlist': [{'artist': {'disambiguation': '',
                         'mbid': 'cc197bad-dc9c-440d-a5b5-d52ba2e14234',
                         'name': 'Coldplay',
                         'sortName': 'Coldplay',
                         'tmid': 806431,
                         'url': 'https://www.setlist.fm/setlists/coldplay-3d6bde3.html'},
              'eventDate': '15-11-2017',
              'id': '33e0845d',
              'info': 'Last show of the A Head Full of Dreams Tour',
              'lastUpdated': '2017-11-23T14:51:05.000+0000',
              'sets': {'set': [{'song': [{'cover': {'disambiguation': '',
                                                    'mbid': '9dee40b2-25ad-404c-9c9a-139feffd4b57',
                                                    'name': 'Maria Callas',
                                                    'sortName': 'Callas, Maria',
                                                    'url': 'https://www.setlist.fm/setlists/maria-callas-33d6706d.html'},
                                          'name': 'O mio babbino caro',
                                          'tape': True},
                                         {'info': 'extended intro with Charlie '
                                                  'Chaplin speech',
                                          'name': 'A Head Full of Dreams'},
                                         {'name': 'Yellow'},
                                         {'name': 'Every Teardrop Is a '
                                                  'Waterfall'},
                                         {'name': 'The Scientist'},
                                         {'info': 'with "Oceans" excerpt in '
                                                  'intro',
                                          'name': 'God Put a Smile Upon Your '
                                                  'Face'},
                                         {'info': 'with Tiësto Remix outro',
                                          'name': 'Paradise'}]},
                               {'name': 'B-Stage',
                                'song': [{'name': 'Always in My Head'},
                                         {'name': 'Magic'},
                                         {'info': 'single version',
                                          'name': 'Everglow'}]},
                               {'name': 'A-Stage',
                                'song': [{'info': 'with "Army of One" excerpt '
                                                  'in intro',
                                          'name': 'Clocks'},
                                         {'info': 'partial',
                                          'name': 'Midnight'},
                                         {'name': 'Charlie Brown'},
                                         {'name': 'Hymn for the Weekend'},
                                         {'info': 'with "Midnight" excerpt in '
                                                  'intro',
                                          'name': 'Fix You'},
                                         {'name': 'Viva la Vida'},
                                         {'name': 'Adventure of a Lifetime'},
                                         {'cover': {'disambiguation': '',
                                                    'mbid': '3f8a5e5b-c24b-4068-9f1c-afad8829e06b',
                                                    'name': 'Soda Stereo',
                                                    'sortName': 'Soda Stereo',
                                                    'tmid': 1138263,
                                                    'url': 'https://www.setlist.fm/setlists/soda-stereo-7bd6d204.html'},
                                          'name': 'De música ligera'}]},
                               {'name': 'C-Stage',
                                'song': [{'info': 'extended',
                                          'name': 'Kaleidoscope',
                                          'tape': True},
                                         {'info': 'acoustic',
                                          'name': 'In My Place'},
                                         {'name': 'Amor Argentina'}]},
                               {'name': 'A-Stage',
                                'song': [{'cover': {'mbid': '2c82c087-8300-488e-b1e4-0b02b789eb18',
                                                    'name': 'The Chainsmokers '
                                                            '& Coldplay',
                                                    'sortName': 'Chainsmokers, '
                                                                'The & '
                                                                'Coldplay',
                                                    'url': 'https://www.setlist.fm/setlists/the-chainsmokers-and-coldplay-33ce5029.html'},
                                          'name': 'Something Just Like This'},
                                         {'name': 'A Sky Full of Stars'},
                                         {'info': 'Extended Outro; followed by '
                                                  '‘Believe In Love’ Tour '
                                                  'Conclusion Video',
                                          'name': 'Up&Up'}]}]},
              'tour': {'name': 'A Head Full of Dreams'},
              'url': 'https://www.setlist.fm/setlist/coldplay/2017/estadio-ciudad-de-la-plata-la-plata-argentina-33e0845d.html',
              'venue': {'city': {'coords': {'lat': -34.9313889,
                                            'long': -57.9488889},
                                 'country': {'code': 'AR', 'name': 'Argentina'},
                                 'id': '3432043',
                                 'name': 'La Plata',
                                 'state': 'Buenos Aires',
                                 'stateCode': '01'},
                        'id': '3d62153',
                        'name': 'Estadio Ciudad de La Plata',
                        'url': 'https://www.setlist.fm/venue/estadio-ciudad-de-la-plata-la-plata-argentina-3d62153.html'},
              'versionId': '7b4ce6d0'},
             {'artist': {'disambiguation': '',
                         'mbid': 'cc197bad-dc9c-440d-a5b5-d52ba2e14234',
                         'name': 'Coldplay',
                         'sortName': 'Coldplay',
                         'tmid': 806431,
                         'url': 'https://www.setlist.fm/setlists/coldplay-3d6bde3.html'},
              'eventDate': '14-11-2017',
              'id': '63e08ec7',
              'info': '"Paradise", "Something Just Like This" and "De música '
                      'ligera" were soundchecked',
              'lastUpdated': '2017-11-15T02:40:25.000+0000',
              'sets': {'set': [{'song': [{'cover': {'disambiguation': '',
                                                    'mbid': '9dee40b2-25ad-404c-9c9a-139feffd4b57',
                                                    'name': 'Maria Callas',
                                                    'sortName': 'Callas, Maria',
                                                    'url': 'https://www.setlist.fm/setlists/maria-callas-33d6706d.html'},
                                          'name': 'O mio babbino caro',
                                          'tape': True},
                                         {'info': 'extended intro with Charlie '
                                                  'Chaplin speech',
                                          'name': 'A Head Full of Dreams'},
                                         {'name': 'Yellow'},
                                         {'name': 'Every Teardrop Is a '
                                                  'Waterfall'},
                                         {'name': 'The Scientist'},
                                         {'info': 'with "Oceans" excerpt in '
                                                  'intro',
                                          'name': 'Birds'},
                                         {'info': 'with Tiësto Remix outro',
                                          'name': 'Paradise'}]},
                               {'name': 'B-Stage',
                                'song': [{'name': 'Always in My Head'},
                                         {'name': 'Magic'},
                                         {'info': 'single version; dedicated '
                                                  'to the Argentinian victims '
                                                  'of the New York terrorist '
                                                  'attack',
                                          'name': 'Everglow'}]},
                               {'name': 'A-Stage',
                                'song': [{'info': 'with "Army of One" excerpt '
                                                  'in intro',
                                          'name': 'Clocks'},
                                         {'info': 'partial',
                                          'name': 'Midnight'},
                                         {'name': 'Charlie Brown'},
                                         {'name': 'Hymn for the Weekend'},
                                         {'info': 'with "Midnight" excerpt in '
                                                  'intro',
                                          'name': 'Fix You'},
                                         {'name': 'Viva la Vida'},
                                         {'name': 'Adventure of a Lifetime'},
                                         {'cover': {'disambiguation': '',
                                                    'mbid': '3f8a5e5b-c24b-4068-9f1c-afad8829e06b',
                                                    'name': 'Soda Stereo',
                                                    'sortName': 'Soda Stereo',
                                                    'tmid': 1138263,
                                                    'url': 'https://www.setlist.fm/setlists/soda-stereo-7bd6d204.html'},
                                          'info': 'Coldplay debut',
                                          'name': 'De música ligera'}]},
                               {'name': 'C-Stage',
                                'song': [{'info': 'Part 1: "The Guest House"',
                                          'name': 'Kaleidoscope',
                                          'tape': True},
                                         {'info': 'acoustic; Will on lead '
                                                  'vocals',
                                          'name': 'In My Place'},
                                         {'info': 'song made for Argentina',
                                          'name': 'Amor Argentina'},
                                         {'info': 'Part 2: "Amazing Grace"',
                                          'name': 'Kaleidoscope',
                                          'tape': True}]},
                               {'name': 'A-Stage',
                                'song': [{'name': 'Life Is Beautiful'},
                                         {'cover': {'mbid': '2c82c087-8300-488e-b1e4-0b02b789eb18',
                                                    'name': 'The Chainsmokers '
                                                            '& Coldplay',
                                                    'sortName': 'Chainsmokers, '
                                                                'The & '
                                                                'Coldplay',
                                                    'url': 'https://www.setlist.fm/setlists/the-chainsmokers-and-coldplay-33ce5029.html'},
                                          'name': 'Something Just Like This'},
                                         {'name': 'A Sky Full of Stars'},
                                         {'name': 'Up&Up'}]}]},

这是我从网址抓取的JSON的一部分。 以下是我正在尝试的代码:

import requests
import json
from pprint import*
url = "https://api.setlist.fm/rest/1.0/artist/cc197bad-dc9c-440d-a5b5-d52ba2e14234/setlists?p=1"

headers = {'x-api-key': 'API-KEY', 
            'Accept': 'application/json'}

r = requests.get(url, headers=headers)
data = json.loads(r.text)
#pprint(r.json())
response = data['setlist']
#pprint(response)
for item in response:
    pprint(item['sets']['set']['song']['name'])

但是我收到此错误,我无法解决,也没有在线找到任何帮助:

    pprint(item['sets']['set']['song']['name'])
TypeError: list indices must be integers or slices, not str

1 个答案:

答案 0 :(得分:0)

  • 字典(Dict)可通过密钥访问。
  • 列表由索引访问。

# Dict get 'item'.
data = {'key': 'item'}
data['key']

# List get 'item0'.
data = ['item0', 'item1']
data[0]

# Dict with List get 'item0'.
data = {'key': ['item0', 'item1']}
data['key'][0]

两种存储类型都可以嵌套在JSON中,并且需要在a中访问 不同的方式。

您有嵌套列表需要编制索引,可以通过以下方式完成 一个for循环。

除了Python不完整的对象外,我无法访问可用的json数据 您显示,所以我没有测试我的代码。因此,不能保证这一点 是正确的。如果没有,它可能会演示如何完成任务。

import requests
import json
from pprint import *
url = "https://api.setlist.fm/rest/1.0/artist/cc197bad-dc9c-440d-a5b5-d52ba2e14234/setlists?p=1"

headers = {'x-api-key': 'API-KEY',
            'Accept': 'application/json'}

r = requests.get(url, headers=headers)
data = json.loads(r.text)

result = []
for setlist_item in data['setlist']:
    for set_item in setlist_item['sets']['set']:
        for song_item in set_item['song']:
            result += [song_item['name']]
print(result)

每个for循环都处理每个列表,最终得到扩展结果 每首歌名。