Python 如何以数字顺序打印带有键的JSON(即字符串键是整数)
我有下面的JSONPython 如何以数字顺序打印带有键的JSON(即字符串键是整数),python,json,python-3.x,Python,Json,Python 3.x,我有下面的JSON { "clips": { "0": { "name": "Please", "id": 1, }, "1": { "name": "Print", "id": 2 }, "10": { "name": "me", "id": 3
{
"clips": {
"0": {
"name": "Please",
"id": 1,
},
"1": {
"name": "Print",
"id": 2
},
"10": {
"name": "me",
"id": 3
},
"2": {
"name": "in order",
"id": 4
}
}
}
这是这样做的:
print(json.dumps(data,sort\u keys=True,indent=4))
这很好,因为它按字母数字顺序打印键。但是,我需要以实际的数字顺序打印这些内容,因此在键“2”
上方的键“10”
之前
我知道python通常不会对字典中的键进行排序,但我需要这样做,因为json实际上会被人类读取,对它进行排序将非常好。谢谢。试试这个
from collections import OrderedDict
ordKeys = sorted([int(x) for x in originalDict.keys()])
newDict = OrderedDict()
for key in ordKeys:
newDict[str(key)] = originalDict[str(key)]
#Print out to JSON
试试这个
from collections import OrderedDict
ordKeys = sorted([int(x) for x in originalDict.keys()])
newDict = OrderedDict()
for key in ordKeys:
newDict[str(key)] = originalDict[str(key)]
#Print out to JSON
这个怎么样:
import json
import collections
a = '''
{"clips":
{
"0":{"name": "Please", "id": 1,},
"1": {"name": "Print", "id": 2,},
"10": {"name": "me", "id": 3,},
"2": {"name": "in order", "id": 4,}
}}
'''
#replace comas before } otherwise json.loads will fail
a = a.replace(',}','}')
#parse json
a = json.loads(a)
#converting keys to int
a['clips'] = {int(k):v for k,v in a['clips'].items()}
#sorting
a['clips'] = collections.OrderedDict(sorted(a['clips'].items()))
print a
这个怎么样:
import json
import collections
a = '''
{"clips":
{
"0":{"name": "Please", "id": 1,},
"1": {"name": "Print", "id": 2,},
"10": {"name": "me", "id": 3,},
"2": {"name": "in order", "id": 4,}
}}
'''
#replace comas before } otherwise json.loads will fail
a = a.replace(',}','}')
#parse json
a = json.loads(a)
#converting keys to int
a['clips'] = {int(k):v for k,v in a['clips'].items()}
#sorting
a['clips'] = collections.OrderedDict(sorted(a['clips'].items()))
print a
您可以使用听写理解技巧:
import json
d = dict({'2':'two', '11':'eleven'})
json.dumps({int(x):d[x] for x in d.keys()}, sort_keys=True)
输出:
'{"2": "two", "11": "eleven"}'
您可以使用听写理解技巧:
import json
d = dict({'2':'two', '11':'eleven'})
json.dumps({int(x):d[x] for x in d.keys()}, sort_keys=True)
输出:
'{"2": "two", "11": "eleven"}'
你基本上是想在从JSON转换后对字典进行排序吗?JSON不能处理整数键吗?@jornsharpe,
JSON
总是这样。@TigerhawkT3但这不是在排序键之后吗?我不确定哪一个先发生,但它看起来像是字符串转换。你基本上是在从JSON转换后对字典进行排序吗?JSON不能处理整数键吗?@jornsharpe,JSON
总是。@TigerhawkT3但这不是在排序键之后吗?我不确定哪一个先发生,但它看起来像是字符串转换。我不知道。。。这显然是最好的答案。请将str(x)改为str(key);另外:如果在下面的json.dump中使用sort_keys=True,那么即使对于OrderedDict[sic!]Beats me,这个顺序也会再次被置乱。。。这显然是最好的答案。请将str(x)改为str(key);另外:如果在下面的json.dump中使用sort_keys=True,那么即使对于OrderedDict[sic!]这个顺序也会被打乱,为什么要使用这种奇怪的方法来生成json文本?为什么不简单地使用以'
或'
分隔的三引号多行字符串?为什么要使用这种奇怪的方法来生成JSON文本?为什么不简单地使用以'
或'
分隔的三引号多行字符串?我不知道字典理解也存在。谢谢你也教了我一些新东西:)另外,为什么转储整型键会导致JSON中出现字符串?@ytpillai整型键是不允许的,所以我相信Python模块会自动转换它们。我不知道字典理解也存在。谢谢你也教了我一些新东西:)另外,为什么转储整型键会导致JSON中出现字符串?@ytpillai整型键是不允许的,所以我相信Python模块会自动转换它们。