我有一个嵌套字典,其中包含json文件中的许多项目:
{
"Create Code For Animals": {
"mammals": {
"dog": {
"color": "brown",
"name": "John",
"legs": "four",
"tail": "yes"
},
"cat": {
"color": "blue",
"name": "Johnny",
"legs": "four",
"tail": "yes"
},
"donkey": {
"color": "grey",
"name": "Mickey",
"legs": "four",
"tail": "yes"
}
我想替换每个动物中的名字,然后将其保存回文件, AND 保持缩进(如图所示)。 我使用以下两种方法来加载和转储原始和更新的字典。
一切正常(用于更改值并将其保存回文件),除了在保存文件后线的缩进(格式)被破坏并且文件被保存为一条长行(用' \ n'显示更新后的值)。
我尝试过使用' pickle' (正如这里的一篇文章中所见),但这没有用,弄乱了文件中的所有数据。
def loadJson(self, jsonFilename):
with open(FILE_PATH + '\\' + jsonFilename, 'r') as f:
return json.load(f)
def writeJson(self, jsonFilename, jsonDict):
with open(FILE_PATH + '\\' + jsonFilename, 'w') as f:
return json.dump(jsonDict, f)
任何帮助都可以。
答案 0 :(得分:4)
json.dumps和dump有一个名为indent的参数
msbuild
这样的事情可以做到:
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation. Since the default item separator is ``', '``, the
output might include trailing whitespace when ``indent`` is specified.
You can use ``separators=(',', ': ')`` to avoid this