[英]extract all Json key values
我不熟悉 Python Json。 我有這些 Json 結果:
{
"href": "https://api.spotify.com/v1/users/wizzler/playlists",
"items": [
{
"collaborative": false,
"external_urls": {
"spotify": "http://open.spotify.com/user/wizzler/playlists/53Y8wT46QIMz5H4WQ8O22c"
},
"href": "https://api.spotify.com/v1/users/wizzler/playlists/53Y8wT46QIMz5H4WQ8O22c",
"id": "53Y8wT46QIMz5H4WQ8O22c",
"images": [],
"name": "Wizzlers Big Playlist",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/wizzler"
},
"href": "https://api.spotify.com/v1/users/wizzler",
"id": "wizzler",
"type": "user",
"uri": "spotify:user:wizzler"
},
"public": true,
"snapshot_id": "bNLWdmhh+HDsbHzhckXeDC0uyKyg4FjPI/KEsKjAE526usnz2LxwgyBoMShVL+z+",
"tracks": {
"href": "https://api.spotify.com/v1/users/wizzler/playlists/53Y8wT46QIMz5H4WQ8O22c/tracks",
"total": 30
},
"type": "playlist",
"uri": "spotify:user:wizzler:playlist:53Y8wT46QIMz5H4WQ8O22c"
},
{
"collaborative": false,
"external_urls": {
"spotify": "http://open.spotify.com/user/wizzlersmate/playlists/1AVZz0mBuGbCEoNRQdYQju"
},
"href": "https://api.spotify.com/v1/users/wizzlersmate/playlists/1AVZz0mBuGbCEoNRQdYQju",
"id": "1AVZz0mBuGbCEoNRQdYQju",
"images": [],
"name": "Another Playlist",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/wizzlersmate"
},
"href": "https://api.spotify.com/v1/users/wizzlersmate",
"id": "wizzlersmate",
"type": "user",
"uri": "spotify:user:wizzlersmate"
},
"public": true,
"snapshot_id": "Y0qg/IT5T02DKpw4uQKc/9RUrqQJ07hbTKyEeDRPOo9LU0g0icBrIXwVkHfQZ/aD",
"tracks": {
"href": "https://api.spotify.com/v1/users/wizzlersmate/playlists/1AVZz0mBuGbCEoNRQdYQju/tracks",
"total": 58
},
"type": "playlist",
"uri": "spotify:user:wizzlersmate:playlist:1AVZz0mBuGbCEoNRQdYQju"
}
],
"limit": 9,
"next": null,
"offset": 0,
"previous": null,
"total": 9
}
現在我只需要提取播放列表 id。 怎么做?
編輯:
我得到 Json 數據:
r = requests.get(BASE_URL + 'users/' + user_id + '/playlists', headers=headers)
r = r.json()
print(r)
將 Json 數據返回給我。 當我嘗試data = json.load(r)
我得到這些錯誤! AttributeError: 'dict' object has no attribute 'read'
首先,使用內置的json
庫加載 JSON 文件。
import json
with open('path/to/json/file.json') as f:
data = json.load(f)
然后,使用列表推導僅獲取 ID。
playlist_ids = [item['id'] for item in data['items']]
編輯:或者,如果您已經解析了 JSON,只需使用列表理解。 不要這樣做r = r.json()
,這會將請求 object 重置為數據。 將其設置為其他變量, data
正常 - data = r.json()
playlist_ids = [item['id'] for item in data['items']]
編輯 2:如果您只想要所有者 ID 為"wizzler"
的位置,則將 if 子句添加到列表理解中。
playlist_ids = [item['id'] for item in data['items'] if item['owner']['id'] == 'wizzler']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.