I've got a json file which contains different 2 layered lists. After every element of the main list, I add a linebreak so you can easily read the data. But when I load the file and make changes to some of the elements in the lists and dump it back in, the indentation is messed up and you can't read it anymore.So how can I make it so that there's a line break after every element of the first layer of the list like before and not after every single element of the second layer list? Thanks for helping me!
My code:
with open("./world_data.json", "r") as f:
data = json.load(f)
new_data = data[level_name] #Accessing the right variable in the json ("level_1_data/"level_2_data")
new_data[button[1][3][1]][button[1][3][0]] = world.block_number #Making changes to the lists
data[level_name] = new_data
data.update(data)
with open("./world_data.json", "w") as f:
json.dump(data, f, indent=4)
Before dumping (the way I want it to look after dumping):
{
"level_1_data": [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 1],
[1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 2, 2, 1]
],
"level_2_data": [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
}
After dumping (I left most of the data out because it would be too long):
{
"level_1_data": [
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
],
[
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
1
]
}