简体   繁体   English

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

[英]How to print sorted data on json.load?

I need to print line for line a static json file. 我需要为一行静态json文件打印一行。 I would like to sort this by a key value prior to printing. 我想在打印之前按键值对它进行排序。 I have looked at several other examples on stackoverflow, but was unable to find a solution to this particular problem. 我看了关于stackoverflow的其他几个示例,但是无法找到解决此特定问题的方法。

My code so far looks like this: 到目前为止,我的代码如下所示:

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

My json looks like this: 我的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"]}
]

How can I sort it by a key value such as "version" while preserving order? 在保留顺序的同时,如何按“ version”之类的键值对其进行排序? In this way I can determine at which version the license was changed. 通过这种方式,我可以确定许可证的版本。

Desired output would look like this: 所需的输出如下所示:

[
{"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"]}
]

Thank you. 谢谢。

You just need to sort your list of dicts with an appropriate key function. 您只需要使用适当的键功能对字典列表进行排序即可。 You could use a lambda, but itemgetter is more efficient. 可以使用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)

output 输出

[   {'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']}]

It looks like the data is already in dictionary form so something like: 看来数据已经是字典形式了,所以像:

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

And then pretty-print that structure. 然后漂亮地打印该结构。

Edit: you can print the whole structure with one line, by the way: 编辑:您可以通过以下方式用一行打印整个结构:

pprint.pprint(sorted_data, indent=4)

should look pretty nice. 应该看起来不错。

For more information on the lambda expression, have a look at this SO thread: What is key=lambda 有关lambda表达式的更多信息,请查看以下SO线程: 什么是key = lambda

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM