简体   繁体   English

Python解析JSON嵌套数据

[英]Python parsing JSON nested data

I am trying to parse this JSON data from the setlist.fm api. 我正在尝试从setlist.fm api解析此JSON数据。 I am trying to get all the song names in order from each setlist. 我正在尝试从每个清单中按顺序获取所有歌曲名称。 I have looked around but none of the methods describe on the internet are working. 我环顾四周,但互联网上描述的所有方法均无效。

Here is the JSON data 这是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'}]}]},

This is part of the JSON I grabbed from the URL. 这是我从URL中获取的JSON的一部分。 Below is the code I am trying touse: 以下是我尝试使用的代码:

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'])

However I get this error that I cannot resolve nor find any help online with: 但是,我收到此错误,无法解决,也无法在线找到任何帮助:

    pprint(item['sets']['set']['song']['name'])
TypeError: list indices must be integers or slices, not str
  • Dictionaries (Dict) are accessed by keys. 通过键可以访问字典(Dict)。
  • Lists are accessed by indexes. 列表通过索引访问。

ie

# 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]

Both storage types can be nested in JSON and either needs to be accessed in a different manner. 两种存储类型都可以嵌套在JSON中,并且每种存储类型都需要以不同的方式进行访问。

You have nested Lists which need to be indexed through and that can be done by a for loop. 您具有需要通过其建立索引的嵌套列表,并且可以通过for循环来完成。

I have no access to workable json data except for the Python incomplete object that you show so I have not tested my code. 除了您显示的Python不完整对象外,我无权访问可行的json数据,因此我尚未测试代码。 Thus, no assurance that this is correct. 因此,不能保证这是正确的。 If not, it may demonstrate how to do the task. 如果没有,它可能会演示如何执行任务。

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)

Each for loop is processing each list to finally get to extending the result with each song name. 每个for循环都在处理每个列表,以最终扩展带有每个歌曲名称的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM