python 如何在for循环中为json添加子项

k7fdbhmy  于 2023-01-01  发布在  Python
关注(0)|答案(2)|浏览(156)

我正在尝试实现以下json输出:

我的当前代码:

#!/usr/bin/env python3.9
import json

complete_lst = []
url_lst = ['https://', 'https://', 'https://']
complete_lst.append({'title': 'Hello'})

for url in url_lst:
  complete_lst.append({'watch': {'Season1': {'url': url}}
                     })

with open("Hello.json", "w") as file:
   json.dump(complete_lst, file)

输出的json文件如下所示:

我希望所有的网址都嵌套在watch->Season1->url键下

sbtkgmzw

sbtkgmzw1#

试试这个:

import json

complete_lst = []
url_lst = ['https://', 'https://', 'https://']
complete_lst.append({
    'title': 'Hello',
    'watch': {'Season1':{"url":[]}}
})

for url in url_lst:
  complete_lst[0]["watch"]["Season1"]["url"].append(url)

print(complete_lst)

如果您的数据是静态的,那么就这样做:

import json

complete_lst = [{
    'title': 'Hello',
    'watch': {'Season1':{"url":['https://', 'https://', 'https://']}}
}]

print(complete_lst)
ct3nt3jp

ct3nt3jp2#

另一种方法是构建字典而不是列表:

#!/usr/bin/env python3.9
import json

complete_lst = []
url_lst = ['https://', 'https://', 'https://']
complete_list = {}
complete_list['title'] = "Hello"
complete_list['watch'] = {}
complete_list['watch']['Season1'] = {}
complete_list['watch']['Season1']['urls'] = []

for url in url_lst:
    complete_list['watch']['Season1']['urls'].append(url)

    
    
with open("Hello.json", "w") as file:
   json.dump(complete_list, file)

注意:这里你不需要通过索引访问条目,可以直接使用键

相关问题