我如何或可以得到 python -mjson.tool 来维护属性的顺序

Bob*_*har 3 python json python-2.7

除了这个简单的调用之外,我对python知之甚少: python -m json.tool {someSourceOfJSON}

请注意源文档如何排序“id”、“z”、“a”,但生成的 JSON 文档显示属性“a”、“id”、“z”。

$ echo '{ "id": "hello", "z": "obj", "a": 1 }' | python -m json.tool
{
    "a": 1,
    "id": "hello",
    "z": "obj"
}
Run Code Online (Sandbox Code Playgroud)

我如何或可以使json.tool事物保持原始 JSON 文档中属性的顺序?

python 版本是这个 MacBookPro 附带的任何版本

$ python --version
Python 2.7.15
Run Code Online (Sandbox Code Playgroud)

Ala*_*ack 5

我不确定是否有可能,python -m json.tool但有一个衬里(我猜这是实际的 X/Y 根问题):

echo '{ "id": "hello", "z": "obj", "a": 1 }' | python -c "import json, sys, collections; print(json.dumps(json.loads(sys.stdin.read(), object_pairs_hook=collections.OrderedDict), indent=4))"
Run Code Online (Sandbox Code Playgroud)

结果:

{
    "id": "hello",
    "z": "obj",
    "a": 1
}
Run Code Online (Sandbox Code Playgroud)

这本质上是以下代码,但没有直接对象和一些可读性妥协,例如单行导入。

import json
import sys
import collections

# Read from stdin / pipe as a str
text = sys.stdin.read()

# Deserialise text to a Python object.
# It's most likely to be a dict, depending on the input
# Use `OrderedDict` type to maintain order of dicts.
my_obj = json.loads(text, object_pairs_hook=collections.OrderedDict)

# Serialise the object back to text
text_indented = json.dumps(my_obj, indent=4)

# Write it out again
print(text_indented)
Run Code Online (Sandbox Code Playgroud)