【发布时间】:2017-12-30 20:08:38
【问题描述】:
我有一个 JSON 对象列表的文件。它看起来像这样:
[
{
"id": 748,
"location": {
"slug": "istanbul",
"parent": {
"id": 442,
"slug": "turkey"
}
},
"rank": 110
},
{
"id": 769,
"location": {
"slug": "dubai",
"parent": {
"id": 473,
"slug": "uae"
}
},
"rank": 24
}
]
我想创建一个酒店父名称列表,所以我编写了这段代码来执行此操作,我读取 JSON 文件并将其分配给一个变量,那部分是正确的。但是看看这段代码:
with open('hotels.json', 'r', encoding="utf8") as hotels_data:
hotels = json.load(hotels_data)
parents_list = []
for item in hotels:
if item["location"]["parent"]["slug"] not in parents_list:
parents_list.append(item["location"]["parent"])
当我运行这段代码时,我给出了这个错误:
if item["location"]["parent"]["slug"] not in parents_list:
TypeError: 'NoneType' object is not subscriptable
这段代码不起作用,所以我尝试打印 JSON 对象,所以我在循环中写了这个:
print(item["location"]["parent"]["slug"])
这段代码打印了我想要的值,但也给了我完全相同的错误。 感谢您的任何帮助。
【问题讨论】:
-
此代码是否因给定示例数据而失败?
-
你用的是python3还是python2?
-
我正在使用 python 3.6
-
您发布的数据中似乎没有出现问题。您可以将 json 文件上传到某处并将链接添加到您的问题吗?
标签: json python-3.x dictionary nested