在读取、修改和写回 JSON 文件时如何保持相同的结构?

How do I maintain the same structure when reading from, modifying and writing back to a JSON file?

我目前正在读取一个 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 是基于 key/value 的结构,顺序无关紧要,但是有没有办法进行修改并保持原始结构?

正如我在评论中所说,您可以在重写文件时使用 collections.OrderedDict along with the optional object_pairs_hook keyword argument accepted by json.load()(在 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.