【问题标题】:How to print JSON with keys in numeric order (i.e. as if the string keys were integers)如何以数字顺序打印带有键的 JSON(即,就好像字符串键是整数一样)
【发布时间】:2015-07-10 20:38:14
【问题描述】:

我有以下 JSON

{
    "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_keys=True, indent=4)) 这很棒,因为它按字母数字顺序打印键。但是,我需要以实际的数字顺序打印这些,因此在键 "2" 上方位于键 "10" 之前。

我知道 python 通常不会对字典中的键进行排序,但我需要这样做,因为 json 实际上会被人类读取并且对其进行排序会很棒。谢谢。

【问题讨论】:

  • 你基本上是在尝试在字典从 JSON 转换后对其进行排序吗?
  • JSON 不能处理整数键吗?
  • @jonrsharpe,json 总是converts keys to strings
  • @TigerhawkT3 但那不是sort_keys之后吗?
  • 我不确定哪个先发生,但看起来是字符串转换。

标签: python json python-3.x


【解决方案1】:

您可以使用字典理解技巧:

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 中生成字符串?
  • @ytpillai 整数键是不允许的,所以我相信 Python 模块会自动转换它们。
【解决方案2】:

试试这个。

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

【讨论】:

  • 打败我......这显然是最好的答案。
  • 请将 str(x) 修复为 str(key);另外:如果在下面的 json.dump 中使用 sort_keys=True,即使是 OrderedDict [原文如此!],这个顺序也会再次被打乱
【解决方案3】:

这个怎么样:

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

【讨论】:

  • 为什么要使用这种奇怪的方法来生成 JSON 文本?为什么不简单地使用以'''""" 分隔的三引号多行字符串?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-09
  • 2015-05-21
  • 2023-03-14
相关资源
最近更新 更多