如何在循环中为JSON添加子项?需将多URL嵌套至watch->Season1->url
问题分析
你的代码当前会生成一个包含多个独立元素的JSON数组:title是单独的元素,每个URL对应一个独立的watch元素,这和你期望的“所有URL嵌套在watch->Season1->url下”完全不符。
修正后的代码(URL以列表形式存放)
如果希望url字段对应所有URL组成的列表,用下面的代码:
#!/usr/bin/env python3.9 import json url_lst = ['https://url1.com', 'https://url2.com', 'https://url3.com'] # 构建单一的结果字典,而非分散的列表元素 result = { 'title': 'Hello', 'watch': { 'Season1': { 'url': url_lst # 直接把URL列表赋值给url键 } } } with open("Hello.json", "w") as file: json.dump(result, file, indent=4) # indent参数让JSON格式化后更易读
对应的预期JSON输出:
{ "title": "Hello", "watch": { "Season1": { "url": [ "https://url1.com", "https://url2.com", "https://url3.com" ] } } }
可选:URL以对象列表形式存放
如果你的需求是每个URL作为Season1下的独立对象,可调整代码如下:
#!/usr/bin/env python3.9 import json url_lst = ['https://url1.com', 'https://url2.com', 'https://url3.com'] result = { 'title': 'Hello', 'watch': { 'Season1': [{'url': url} for url in url_lst] } } with open("Hello.json", "w") as file: json.dump(result, file, indent=4)
对应的JSON输出:
{ "title": "Hello", "watch": { "Season1": [ {"url": "https://url1.com"}, {"url": "https://url2.com"}, {"url": "https://url3.com"} ] } }
内容的提问来源于stack exchange,提问作者ghost239
相关产品推荐
相关产品推荐

