【问题标题】:Write a JSON object back to .json file with order in Python在 Python 中按顺序将 JSON 对象写回 .json 文件
【发布时间】: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


    【解决方案1】:

    JSON 文件不能真正表明字典是否应该排序;但是,您可以通过使用json.dump 很好地写入带有OrderedDict 的文件,并且键的顺序应该被保留

    with open("testJSON.json", 'w') as f:
        json.dump(jsonObj, f)
    

    如果你想要更漂亮的输出,例如添加indent=4:

    with open("testJSON.json", 'w') as f:
        json.dump(jsonObj, f, indent=4)
    

    【讨论】:

    • @Taihouuuuuuuuuuu 你可以考虑接受我的回答
    • 对不起,我在等待 10 分钟的限制
    猜你喜欢
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多