Python 在for循环中创建嵌套Json
我想在python中创建一个类似于bellow的Json文件Python 在for循环中创建嵌套Json,python,json,Python,Json,我想在python中创建一个类似于bellow的Json文件 { 'Query': 'Pages', 'items': [ { 'url': 'https://stackoverflow.com/', 'Title': 'Stack Overflow Share', 'Description': 'Stack Overflow is the largest, most trusted online community for developer
{
'Query': 'Pages',
'items': [
{
'url': 'https://stackoverflow.com/',
'Title': 'Stack Overflow Share',
'Description': 'Stack Overflow is the largest, most trusted online community for developers to learn, share their programming knowledge, and build their careers'
},
{
'url': 'https://en.wikipedia.org/wiki/Main_Page',
'Title': 'Wikipedia, the free encyclopedia',
'Description': 'Main page'
}
]
}
然而,我远远没有做到这一点:
import json
response_json = {}
items = []
# This list bellow is generated in a for loop (with append to a list) if you have a suggestion how I could do this in a dictionary and use it in the for loop bellow
urls=["https://stackoverflow.com/", "https://en.wikipedia.org/wiki/Main_Page"]
Title=["https://stackoverflow.com/", "Wikipedia, the free encyclopedia"]
Description=["Stack Overflow is the largest","Main page"]
for item in Dictornary_Maybe:
items.append({"url" : item[url],
"Title" : Title,
"Description" : Description
)
response_json["items"] = items
with open('2result.json', 'w') as fp:
json.dump(response_json, fp)
正如你所看到的,这是行不通的,我不知道如何继续下去,假设所有列表的长度都是相同的(它们需要这样才能起作用)
items=[]
URL=[”https://stackoverflow.com/", "https://en.wikipedia.org/wiki/Main_Page"]
标题=[”https://stackoverflow.com/“,“维基百科,免费百科全书”]
Description=[“堆栈溢出最大”,“主页面”]
对于范围内的索引(len(url)):
append({“url”:url[索引],
“标题”:标题[索引],
“说明”:说明[索引]
)
这将为您提供所需格式的项数组。您可以执行以下操作:
导入json
URL=[”https://stackoverflow.com/", "https://en.wikipedia.org/wiki/Main_Page"]
Title=[“Stackoverflow”,“维基百科,免费百科全书”]
Description=[“堆栈溢出最大”,“主页面”]
#进行一些修改以获取字典的项目列表:
keys=['url','title','description']
items=[在zip(URL、标题、描述)中对u、t、d进行dict(zip(键[u、t、d]))
#创建输出dict
d={
“查询”:“页面”,
“项目”:项目
}
#从dict生成一个漂亮的json字符串
d=json.dumps(d,缩进=4)
#将字符串写入txt文件
以fobj形式打开(文件“w”):
fobj.write(d)
这将为您提供一个包含
{
"Query": "Pages",
"items": [
{
"url": "https://stackoverflow.com/",
"title": "Stackoverflow",
"description": "Stack Overflow is the largest"
},
{
"url": "https://en.wikipedia.org/wiki/Main_Page",
"title": "Wikipedia, the free encyclopedia",
"description": "Main page"
}
]
}
总的来说,看看dict
(这里还有zip
)能提供什么。我认为这里的关键是创建/使用dict。将dict转储到json
(或其他)只是管道末端的内容。作为更一般的考虑,“并行列表”(两个或多个按索引匹配的列表)是一个非常脆弱的数据结构。更改其中一个列表,映射就会被破坏。DICT或元组列表(实际上正是您试图为json导出所做的)是一个更理智的数据结构。@brunodesthuilliers非常感谢,将对此进行研究。