簡體   English   中英

Python-Json編寫,不想按我的意願打印

[英]Python - Json write, Doesn't want to print out as I wish

我試圖從我的腳本中進行寫操作以使其成為Json文件。

但是,當我用腳本寫出來時,它的輸出為

{
    "profile_1": {
        "email": "HelloWorld",
        "pswrd": "WorldHello123"
    }
} {
    "profile_2": {
        "email": "HelloWorld",
        "pswrd": "WorldHello123"
    }
} {
    "profile_3": {
        "email": "HelloWorld",
        "pswrd": "WorldHello123"
    }
}

我真正希望的是:

"profile_0": {
            "email": "HelloWorld",
            "pswrd": "WorldHello123"

        },
        "profile_1": {
            "email": "HelloWorld",
            "pswrd": "WorldHello123""
        },
        "profile_2": {
            "email": "HelloWorld",
            "pswrd": "WorldHello123"
        },
        "profile_3": {
            "email": "HelloWorld",
            "pswrd": "WorldHello123"
        },

而且,根據我們的比較,{}太多了,而且也缺少了,我不太明白為什么它行不通。 這是我的腳本的工作方式:

import json

    with open("test.txt") as accounts:
        for splitlines in accounts:
            temp = accounts.read().splitlines()
            username, password = zip(*(s.split(":") for s in temp))
            linelength = len(username)

            with open("profiles.json", "a") as profile:
                lineInt = 0
                while (lineInt < linelength):
                    lineInt += 1
                    jsonData = {
                            "profile_" + str(lineInt): {
                            "email": username[lineInt],
                            "pswrd": password[lineInt]
                            }
                    }
                    json.dump(jsonData, profile)

我坐了太久沒看到問題了:'(

您正在逐一輸出JSON對象 如果要輸出JSON數組 ,則應將對象放在列表中,並進行打印,例如:

lineInt = 0
items = []
while (lineInt < linelength):
    jsonData = {
        "profile_" + str(lineInt): {
            "email": username[lineInt],
            "pswrd": password[lineInt]
        }
    }
    lineInt += 1
    items.append(jsonData)
json.dump(items, profile)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM