filassy
filassy

Reputation: 3

Removing excess square brackets when dumping to JSON multiple times

For every time I dump a dictionary into a JSON file, a pair of square brackets is added, which I cannot figure out how to avoid.

I use "try" to write to an existing JSON file (where the issue arises), and except JSONDecodeError to write to an empty JSON file. Code looks like:

allgrades = []

[...]

    currentgrades = {f"name": students_name,
            "grade": students_grade,
            "date": date.strftime("%Y-%m-%d %H:%M:%S")
        }
    
    allgrades.append(currentgrades)
    # Write json file

with open("grades.json", "r") as infile:
    try:
        grades = json.load(infile)
        infile.close()
        grades.append(allgrades)
        with open("grades.json", "w") as outfile:
            json.dump(grades, outfile)
    except JSONDecodeError:
        with open("grades.json", "w") as outfile:
            json.dump(allgrades, outfile)

And the JSON file after running py twice with 1 exported dict each looks like:

[{"name": "person1", "grade": "4", "date": "2021-02-20 10:42:01"}, [{"name": "person2", "grade": "4", "date": "2021-02-20 10:52:52"}]]

Is there a way I can end up with a JSON file that is only surrounded by one single pair of square brackets, no matter how many times I add to the JSON? I.e.

[{"name": "person1", "grade": "4", "date": "2021-02-20 10:42:01"}, {"name": "person2", "grade": "4", "date": "2021-02-20 10:52:52"}]

Upvotes: 0

Views: 606

Answers (1)

rdas
rdas

Reputation: 21275

grades.append(allgrades)

allgrades is a list, which you're appending to grades - another list. This creates a nested list which is where the extra ] is from.

What you want is to extend the existing list with the new one:

grades.extend(allgrades)

Which adds all the entries in allgrades to grades - without any nesting.

Upvotes: 1

Related Questions