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

时间:2019-02-06 17:13:03

标签: 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"
}

如何使json.tool东西保持原始JSON文档中属性的顺序?

此MacBookPro随附的版本均为python版本

$ python --version
Python 2.7.15

1 个答案:

答案 0 :(得分:4)

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

这基本上是下面的代码,但没有立即对象和某些可读性的折衷,例如oneline导入。

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)