繁体   English   中英

在 for 循环中创建嵌套 Json

[英]Created nested Json in for loop

我想在 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)

如您所见,这不是,正在工作,我不知道如何继续

你可以这样做:

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"
        }
    ]
}

假设所有列表的长度都是相同的(它们需要这样才能工作)

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数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM