2017-12-24 2 views
0

setlist.fm api에서이 JSON 데이터를 구문 분석하려고합니다. 각 세트리스트에서 모든 노래 이름을 순서대로 얻으려고합니다. 나는 주변을 둘러 보았지만 인터넷에서 설명하는 방법 중 어느 것도 작동하지 않습니다. 여기 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'}]}]}, 

이 내가 URL에서 움켜 JSON의 일부입니다. 다음은 내가 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']) 

나는 온라인으로 해결하거나 도움을 찾을 수없는이 오류를 얻을 그러나 : 키에 액세스하는

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

JSON의 구조를 먼저 이해하지 않고도 해결할 수있는 오류는 아닙니다. 거기에는 사전이 아니라 목록이 있습니다. –

+0

'item [ 'sets'] [ 'set']'당신이 질문에 게시 한 json에 따른 목록입니다. –

답변

0
  • 사전 (DICT를) .
  • 목록은 인덱스로 액세스됩니다. 두 스토리지 유형 JSON 중첩하고 필요하거나 할 수있다, 즉

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

는 다른 방식으로 액세스한다.

색인을 생성해야하는 중첩 목록이 있으며 for 루프로 완료 할 수 있습니다.

파이썬 불완전 객체 을 제외하고 실행할 수있는 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) 

루프 각

최종적 각 곡명으로 결과를 얻을 연장 각각에서 처리된다.

+0

아 감사합니다. 나는리스트를 완전히 잊었다. 당신의 대답을 약간 수정하고 중첩 루프를 다음과 같이 편집해야했습니다 :'set_item [ 'song']의 song_item에서 : print (song_item [ 'name'])' –

+0

모든 도움을 감사하십시오! –

관련 문제