如何或可以让python-mjson.tool维护属性的顺序

如何或可以让python-mjson.tool维护属性的顺序,python,json,python-2.7,Python,Json,Python 2.7,除了这个简单的调用之外,我对python知之甚少:python-mjson.tool{someSourceOfJSON} 注意源文档的顺序是“id”、“z”、“a”,但生成的JSON文档显示属性“a”、“id”、“z” 我如何或可以使json.tool东西保持原始json文档中属性的顺序 python版本是MacBookPro附带的任何版本 $ python --version Python 2.7.15 我不确定是否可以使用python-mjson.tool,但是使用一行程序(我猜这是实际的

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

注意源文档的顺序是“id”、“z”、“a”,但生成的JSON文档显示属性“a”、“id”、“z”

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

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

$ python --version
Python 2.7.15

我不确定是否可以使用
python-mjson.tool
,但是使用一行程序(我猜这是实际的X/Y根问题):

结果:

{
    "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)

sort\u keys=False
json.tool
,不确定如何将其传递到模块tho。这很奇怪,因为他们加了一个旗子,这个旗子实际上是用来。您运行的是旧版本的python吗?因为问题是,如果json工具返回一个字典,那么顺序就会被破坏。你的目标是什么?从3.7开始,Python字典只维护键的输入顺序。早期版本则不然。@BoarGules解释了这一点,在这里默认运行3.7.2。很好。这离我只有一个别名,我再也不明白这是怎么回事了;)。我真的应该学习一些Python。@BobKuhar我已经更新了答案,并解释了为什么会这样。我希望这对您介绍Python有所帮助
{
    "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)