在Python中使用多个数组浏览JSON
我试图使用python遍历JSON,但无法访问“mbid”节点。我只想打印第一个“mbid”节点 以下是我的功能:在Python中使用多个数组浏览JSON,python,json,python-3.x,api,Python,Json,Python 3.x,Api,我试图使用python遍历JSON,但无法访问“mbid”节点。我只想打印第一个“mbid”节点 以下是我的功能: def get_data(): newJsonx = dict() for item in data["resultsPage"]["results"]["calendarEntry"]: mbid = item["event"]["performance"][0]["artist"]["identifier"][0]["mbid"] 使用此函数,
def get_data():
newJsonx = dict()
for item in data["resultsPage"]["results"]["calendarEntry"]:
mbid = item["event"]["performance"][0]["artist"]["identifier"][0]["mbid"]
使用此函数,我会出现以下错误:indexer错误:列表索引超出范围
但是当我做的时候
def get_data():
newJsonx = dict()
for item in data["resultsPage"]["results"]["calendarEntry"]:
mbid = item["event"]["performance"][0]["artist"]["identifier"]
而print(mbid)
,我得到了一个正确的答案:
"identifier": [
{
"mbid": "6655955b-1c1e-4bcb-84e4-81bcd9efab30"
},
{
"mbid": "1b1b1b1b-1c1d"
}
]
这意味着我对数据没有问题。也许我在第二个数组上做错了什么
以下是JSON结构的一个示例:
{
"resultsPage": {
"status": "ok",
"results": {
"calendarEntry": [
{
"reason": {
},
"event": {
"performance": [
{
"id": 72641494,
"displayName": "Arnalds",
"artist": {
"id": 590465,
"identifier": [
{
"mbid": "6655955b-1c1e-4bcb-84e4-81bcd9efab30"
},
{
"mbid": "1b1b1b1b-1c1d"
}
]
}
}
]
}
}
]
}
}
}
感谢您的时间您的第一个函数在您的示例中适用于我。无法复制,对我来说工作正常,您的完整数据JSON必须有一些值丢失或空列表,这使得
[0]
为您提供了error@OferSadan你说得对,有时我有空列表您的第一个函数在您的示例中对我有效。无法复制,对我来说工作正常,您的完整数据JSON必须有一些值丢失或空列表,这使得[0]
为您提供了error@OferSadan你说得对,有时候我的名单是空的
def get_data():
newJsonx = dict()
for item in data["resultsPage"]["results"]["calendarEntry"]:
performance=item["event"]["performance"]
if performace:
identifier=performace[0]["artist"]["identifier"]
if identifier:
mbid=identifier[0]["mbid"]