如何在json.load上打印排序数据?

时间:2016-11-29 14:10:11

标签: python json sorting

我需要打印一行静态json文件。我想在打印之前通过键值对其进行排序。我已经查看了stackoverflow上的其他几个示例,但无法找到解决此特定问题的方法。

到目前为止我的代码看起来像这样:

import json
from pprint import pprint
with open('items.json') as data_file:
    data = json.load(data_file)
    for line in data:
        pprint(data)

我的json看起来像这样:

[
{"version": ["2.8.2"], "license": ["GPL"]},
{"version": ["1.8.8"], "license": ["MIT/X11 License"]},
{"version": ["2.8.5"], "license": ["GPL"]},
{"version": ["1.8.9"], "license": ["MIT/X11 License"]}
]

如何按键值排序,例如" version"在保留秩序的同时? 通过这种方式,我可以确定许可证的更改版本。

所需的输出如下所示:

[
{"version": ["1.8.8"], "license": ["MIT/X11 License"]},
{"version": ["1.8.9"], "license": ["MIT/X11 License"]},
{"version": ["2.8.2"], "license": ["GPL"]},
{"version": ["2.8.5"], "license": ["GPL"]}
]

谢谢。

2 个答案:

答案 0 :(得分:1)

您只需要使用适当的键功能对您的词典列表进行排序。你可以使用lambda,但itemgetter效率更高。

import json
from pprint import pprint
from operator import itemgetter

data_str = '''\
[
    {"version": ["2.8.2"], "license": ["GPL"]},
    {"version": ["1.8.8"], "license": ["MIT/X11 License"]},
    {"version": ["2.8.5"], "license": ["GPL"]},
    {"version": ["1.8.9"], "license": ["MIT/X11 License"]}
]
'''

data = json.loads(data_str)
data.sort(key=itemgetter("version"))
pprint(data)

<强>输出

[   {'license': ['MIT/X11 License'], 'version': ['1.8.8']},
    {'license': ['MIT/X11 License'], 'version': ['1.8.9']},
    {'license': ['GPL'], 'version': ['2.8.2']},
    {'license': ['GPL'], 'version': ['2.8.5']}]

答案 1 :(得分:0)

看起来数据已经是字典形式,如:

sorted_data = sorted(data, key = lambda x: x['version'])

然后漂亮地印刷那个结构。

编辑:顺便说一下,您可以用一行打印整个结构:

pprint.pprint(sorted_data, indent=4)

应该看起来很漂亮。

有关lambda表达式的更多信息,请查看此SO线程:What is key=lambda