簡體   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