将字典结果从一个FOR循环写入JSON文件

时间:2020-03-11 14:01:59

标签: python json

标题可能会引起误解,我想不出一种更好的说法:(。

我正在尝试将字典键和值写入JSON格式的JSON文件中。

示例:

{
    key1: value1
    key2: value1
},

{
    key1: value2
    key2: value2
}

依此类推。

我正在尝试在FOR循环中实现此结果。

这是我当前拥有的代码:

for row in CSVR:
    if totalCSV == 0:
        # Not important for this question
    else:
        soup = BeautifulSoup(row[0], "html.parser") # Parsing results from CSV file using BeautifulSoup

        confirmationNumber = remover(getConfirmationNumber(soup)) # Get confirmation number from a person
        answersQuestions = remover(getQuestionsAndAnswers(soup)) # Get their question

        answersQuestions = answersQuestions.strip() # Strip leading or trailing spaces

        aa = {
        "Confirmation Number": confirmationNumber,
        "Message": answersQuestions
        }

        with open(bdPath, "w") as f:
            json.dump(aa, f, indent = 4) # Write to JSON file

aa 是我正在使用的词典。变量 confirmationNumber answersQuestions 随FOR循环而变化。

在我正在写结果的文件中,我只从FOR循环中获得了最后一个结果,而不是全部。

如果有办法,我该如何解决此问题和/或使此代码更好?

1 个答案:

答案 0 :(得分:2)

您需要在循环后编写JSON文件,并通过将它们“存储”在列表中来跟踪aa

results = []
for row in CSVR:
    if totalCSV == 0:
        # Not important for this question
    else:
        soup = BeautifulSoup(row[0], "html.parser") # Parsing results from CSV file using BeautifulSoup

        confirmationNumber = remover(getConfirmationNumber(soup)) # Get confirmation number from a person
        answersQuestions = remover(getQuestionsAndAnswers(soup)) # Get their question

        answersQuestions = answersQuestions.strip() # Strip leading or trailing spaces

        results.append({
            "Confirmation Number": confirmationNumber,
            "Message": answersQuestions
        })

with open(bdPath, "w") as f:
    json.dump(results, f, indent = 4) # Write to JSON file