Python 需要帮助从循环创建JSON,但格式不正确吗

Python 需要帮助从循环创建JSON,但格式不正确吗,python,json,Python,Json,我正在尝试创建一个Python脚本,从包含数据的文本文件创建JSON taskCount = 0 while (taskCount < 5): stock = { "serial": serial[counter], "price": price[counter], }, taskCount += 1 with

我正在尝试创建一个Python脚本,从包含数据的文本文件创建JSON

taskCount = 0

while (taskCount < 5):
        stock = {
                "serial": serial[counter],
                "price": price[counter],
             },
        taskCount += 1
        with open('tasks.json', 'a') as outfile:
            json.dump(stock, outfile)
    counter += 1
我希望它显示为

[{"serial": "1", "price": "1"},{"serial": "2", "price": "2"},{"serial": "3", "price": "3"},{"serial": "4", "price": "4"},{"serial": "5", "price": "5"}]
每个条目都用分隔,除开头和结尾外,每个条目上都没有[]。我想我是在正确的轨道上,但也许有一个简单的方法可以做到这一点

编辑:修复了其他人出现此问题时的代码

myList = []
taskCount = 0

while (taskCount < 5):
        stock = {
                "serial": serial[counter],
                "price": price[counter],
             },
        taskCount += 1
        myList.append(stock)
    counter += 1
with open('tasks.json', 'a') as outfile:
     json.dump(myList, outfile)
myList=[]
任务计数=0
而(任务数<5):
股票={
“串行”:串行[计数器],
“价格”:价格[柜台],
},
任务计数+=1
myList.append(股票)
计数器+=1
以open('tasks.json','a')作为输出文件:
json.dump(myList,outfile)

您应该将每个“股票”附加到一个列表中,最后在末尾将列表作为json写入文件一次。这样做很有效。非常感谢。
myList = []
taskCount = 0

while (taskCount < 5):
        stock = {
                "serial": serial[counter],
                "price": price[counter],
             },
        taskCount += 1
        myList.append(stock)
    counter += 1
with open('tasks.json', 'a') as outfile:
     json.dump(myList, outfile)