When I add one attribute to my JSON file, I want its dictionary to be ordered. So, I use this:
data[player] = json.loads(thisdata, object_pairs_hook=OrderedDict)
This works fine, except the case when I try to write data (JSON object) back to .json file.
Here, jsonObj == data
file = open("testJSON.json", 'w+')
output = ""
for x in range(0, len(str(jsonObj))):
if (str(jsonObj)[x] == "{"):
output = output + "{" + "\n"
elif (str(jsonObj)[x] == "}"):
output = output + "\n" + "}" + "\n"
elif (str(jsonObj)[x] == ","):
output = output + "," + "\n"
elif (str(jsonObj)[x] == "\'"):
output = output + "\""
else:
output = output + str(jsonObj)[x]
file.write(output)
file.close()
The .json output file is like this:
{
"Noob": OrderedDict([("HP",
10),
("MP",
5),
("STR",
6)]),
"Saber": {
"STR": 10,
"MP": 50,
"HP": 100
}
,
"Archer": {
"STR": 8,
"MP": 40,
"HP": 80
}
}
As you can see, OrderedDict does not work in this case.
I know that I can parse this string by hand, but that is too painful and might not be the most efficient way to do so.
Are there any efficient way to write back to .json file, with ordered dictionary?
A JSON file cannot really signal whether the dictionaries should be ordered or not; however, you can very well write the file with an OrderedDict
by just using json.dump
, and the ordering of the keys should be preserved:
with open("testJSON.json", 'w') as f:
json.dump(jsonObj, f)
If you want prettier output, add for example indent=4
:
with open("testJSON.json", 'w') as f:
json.dump(jsonObj, f, indent=4)