在for循环中创建嵌套的Json

时间:2019-10-15 10:05:33

标签: python json

我想在python中创建像下面这样的Json文件

{
  '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)

如您所见,这是行不通的,而且我不知道如何继续进行

2 个答案:

答案 0 :(得分:2)

您可以这样做:

import json

urls = ["https://stackoverflow.com/", "https://en.wikipedia.org/wiki/Main_Page"]
Title = ["Stackoverflow", "Wikipedia, the free encyclopedia"]
Description = ["Stack Overflow is the largest", "Main page"]

# a bit of modification to get the items list of dictionaries:
keys = ['url', 'title', 'description']
items = [dict(zip(keys, [u, t, d])) for u, t, d in zip(urls, Title, Description)]

# create the output dict
d = {
      'Query': 'Pages',
      'items': items
    }

# make a pretty json string from the dict
d = json.dumps(d, indent=4)

# write the string to a txt file
with open(file, 'w') as fobj:
    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"
        }
    ]
}

答案 1 :(得分:1)

假设所有列表的长度都相同(要使它们起作用,它们必须是这样的)

items = []
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 index in range(len(urls)):
    items.append({"url" : url[index],
                     "Title" : Title[index],
                     "Description" : Description[index]
                     )

这应该以所需的格式为您提供items数组。