【发布时间】:2018-10-30 13:46:03
【问题描述】:
当我向我的 JSON 文件添加一个属性时,我希望对其字典进行排序。所以,我用这个:
data[player] = json.loads(thisdata, object_pairs_hook=OrderedDict)
这很好用,除了我尝试将数据(JSON 对象)写回 .json 文件的情况。
这里,jsonObj == 数据
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()
.json 输出文件是这样的:
{
"Noob": OrderedDict([("HP",
10),
("MP",
5),
("STR",
6)]),
"Saber": {
"STR": 10,
"MP": 50,
"HP": 100
}
,
"Archer": {
"STR": 8,
"MP": 40,
"HP": 80
}
}
如您所见,OrderedDict 在这种情况下不起作用。
我知道我可以手动解析这个字符串,但这太痛苦了,可能不是最有效的方法。
是否有任何有效的方法可以使用有序字典写回 .json 文件?
【问题讨论】:
标签: python json ordereddictionary