data_garden data_garden - 3 months ago 8
JSON Question

Python - iterate over JSON results

In order to get

energy
values, I am trying to iterate over this
JSON
result:

[{u'track_href': u'https://api.spotify.com/v1/tracks/7603o589huckPbiELnUKgu', u'analysis_url': u'https://api.spotify.com/v1/audio-analysis/7603o589huckPbiELnUKgu', u'energy': 0.526, u'liveness': 0.0966, u'tempo': 92.979, u'speechiness': 0.103, u'uri': u'spotify:track:7603o589huckPbiELnUKgu', u'acousticness': 0.176, u'instrumentalness': 0.527, u'time_signature': 4, u'danceability': 0.635, u'key': 1, u'duration_ms': 172497, u'loudness': -8.073, u'valence': 0.267, u'type': u'audio_features', u'id': u'7603o589huckPbiELnUKgu', u'mode': 1},...}]


I'm using list comprehension:

[x['energy'] for x in features]


But I'm getting the following error:

print ([x['energy'] for x in features])
TypeError: 'NoneType' object has no attribute '__getitem__'


What am I doing wrong here?

Answer

It is because within your JSON array, at some place instead of dictionary a None value is present. You may eliminate it via:

[x['energy'] for x in features if x]