【问题标题】:indent is broken after saving back updated json dict to file将更新的 json dict 保存回文件后缩进被破坏
【发布时间】:2016-10-07 09:59:49
【问题描述】:

我有一个嵌套字典,其中包含 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"
        }

我想替换每只动物的名字,然后将其保存回文件中,保持缩进不变(如图所示)。 我正在使用以下 2 种方法来加载和转储原始和更新的字典。

一切正常(用于更改值并将其保存回文件),但保存文件后行的缩进(格式)被破坏并且文件保存为一个长行(带有'\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)          

任何帮助都可以。

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    json.dumps 和 dump 有一个参数叫做 indent

    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
    

    这样的事情会做:

    json.dump(jsonDict,f,indent=4)
    

    【讨论】:

    • 太棒了!在职的!知道如何去掉更新值末尾的 '\n' 吗?
    • 抱歉没看懂评论你的意思是文件末尾的新行吗?
    • 完全正确。新行。它显示在更新值之后。其他值保持不变(因为它们没有更新)
    • 好吧,如果你缩进你会得到新的行。这是无法避免的。如果您收到过多的新行,请尝试使用分隔符
    • 当然这都是装饰性的,json文件中的空格数根本没有关系
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 2020-07-20
    相关资源
    最近更新 更多