Python - Json写道,不想按我的意愿打印出来

时间:2017-10-29 14:09:37

标签: python json

我试图从我的脚本写一个来写它成为一个Json文件。

然而,当我用我的脚本写出来时,它给了我一个输出

"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)

并且正如我们所比较的那样,{}太多了,也缺少哪些我不太明白它为什么不起作用。这就是我的脚本的工作方式:

Dim const path As String = "\Windows\System32\user32"
Private Declare Function CallWindowProcW Lib path...

我坐得太久都没有看到问题:'(

1 个答案:

答案 0 :(得分:0)

您正在逐个输出 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)