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



除了这个简单的调用之外,我对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"
}

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

python版本是MacBookPro附带的任何内容

$ python --version
Python 2.7.15

我不确定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))"

结果:

{
    "id": "hello",
    "z": "obj",
    "a": 1
}

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

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)

最新更新