我正在尝试从 Python 3.7 中的 json 文件制作的字典中创建一个列表。json 文件具有以下结构:watches collection model 0 {…} 1 rmc 0 "value_I_need" 1 "value_I_need"json 提取:{"watches":{"collection":{"event_banner":{"type":"banner","margin":false,"mobile_layer":true,"class":"tdr-banners-events","media":{"type":"image","src":"/public/banners/events/baselworld_2017_navigation.jpg","height":"150px"},"text":{"align":"left","animate":true,"positioning":"left","suptitle":"BANNER_EVENT_A_TITLE","title":"BANNER_EVENT_A_SUPTITLE","title_type":"h2","style":"light","link_text":"BANNER_EVENT_A_LINK_TEXT","link_href":"/magazine/article/baselworld-2017"}},"collection-navigation":{"type":"view","template":"nav.tdr-collection-navigation.tdr-flex.tdr-flex--align-items-center > ul.tdr-collection-navigation__list.tdr-flex.tdr-flex--align-items-flex-start@list","children":[{"type":"view","template":"li.tdr-collection-navigation__item","insert":{"where":"list"},"children":[{"type":"button-gamma","text":"FIND_YOUR_TUDOR_COLLECTION","href":"/search","cssClass":"tdr-button--gamma-collection-navigation","children":[{"type":"new-print(documents)我构建列表的代码:with open('test.json', 'r') as f: dictionary = json.load(f)documents = dictionary["watches"]["collection"]["model"]for document in documents: models = document["rmc"] try: for model in models: start_urls.append('https://www.example.com/'+document['page_link']+'/'+model+'.html') except Exception: pass回溯错误:models = document["rmc"]TypeError: string indices must be integersrmc 值是模型列表中的另一个列表。所以每个模型可能有另一个 rmc 值列表。我的目标是创建所有模型的列表,包括它们的变体 (rmc)。为什么 pyhton 告诉我它是一个字符串,而我相信 rmc 行以整数形式列出?
3 回答
慕少森
TA贡献2019条经验 获得超9个赞
你似乎认为你的model价值是一个列表。JSON 另有说明:
"model":{"0":{"route":"black-bay-32-36-41",
这是一个字典,其键是字符串。你迭代那个字典:
for document in documents:
当您以这种方式遍历 dict 时,您会遍历该 dict的键,因此document保留了 string "0"。该字符串不能被另一个字符串作为 索引document['rmc'],所以 Python 正确地抱怨。
您可以通过几种方式修复它。首先,您可以更改读取模型的方式:
for document in documents:
models = documents[document]['rmc']
...
或者您可以更改遍历 dict 的方式:
for idx, document in documents.items():
models = document['rmc']
漂亮地打印 JSON 而不是将其保留为一个难以理解的行可能会更快地提醒您注意这个问题。
九州编程
TA贡献1785条经验 获得超4个赞
改变这一行:
documents = dictionary['watches']['collection']['model']
对此:
documents = dict(dictionary['watches']['collection']['model'])
并且文档会变成字典
添加回答
举报
0/150
提交
取消