我目前正在读取JSON文件,添加密钥并使用此过程将其写回到同一文件中
with open('data.json', 'r+') as f:
data = json.load(f)
temp_key={"test":"val"}
data["test"]["new_key"] = temp_key
f.seek(0) # <--- should reset file position to the beginning.
json.dump(data, f, indent=2)
f.truncate() # remove remaining part
(从here采纳)
,但是问题在于它不维护顺序。例如,如果我读入:
{
"test": {
"something": "something_else"
},
"abc": {
"what": "huh"
}
}
输出结果为:
{
"abc": {
"what": "huh"
},
"test": {
"something": "something_else",
"new_key": {
"test": "val"
}
}
}
当我希望成为这样的时候:
{
"test": {
"something": "something_else",
"new_key": {
"test": "val"
}
},
"abc": {
"what": "huh"
}
}
我认识到JSON是基于键/值的结构,顺序无关紧要,但是有没有办法进行修改并保持原始结构呢?
答案 0 :(得分:1)
正如我在评论中所说,您可以将collections.OrderedDict
与json.load()
接受的可选object_pairs_hook
关键字参数一起使用(在python 2.7中),以保留原始数据的顺序当您重写文件时。
这就是我的意思:
#!/usr/bin/env python2
from collections import OrderedDict
import json
with open('ordered_data.json', 'r+') as f:
data = json.load(f, object_pairs_hook=OrderedDict)
temp_key = {"test": "val"}
data["test"]["new_key"] = temp_key
f.seek(0) # Reset file position to the beginning.
json.dump(data, f, indent=2)
f.truncate() # Remove remaining part.