简体   繁体   中英

Python parsing JSON nested data

I am trying to parse this JSON data from the setlist.fm api. 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

    {'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. 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.
  • 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.

You have nested Lists which need to be indexed through and that can be done by a for loop.

I have no access to workable json data except for the Python incomplete object that you show so I have not tested my code. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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