首页 > 解决方案 > 将一个 FOR 循环中的字典结果写入 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是我正在使用的字典。变量ConfirmationNumberanswersQuestions取决于 FOR 循环。

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

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

标签: pythonjson

解决方案


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

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

推荐阅读