简体   繁体   English

Python根据字典数组中的键对json排序

[英]Python sort a json based on a key inside an array of dictionary

I have a structure like this: 我有这样的结构:

[{
    "name": "apple",
    "price": "5.0",
    "record": [
        {
            "id": "008",
            "time": 1465689600
        }
    ] 
},{
    "name": "banana",
    "price": "9.0",
    "record": [
        {
            "id": "002",
            "time": 1465682600
        }
    ]
}]

I tried below but it gave me an error: string indices must be integers. 我在下面尝试过,但是给了我一个错误:字符串索引必须是整数。

sorted(lines, key=lambda k: k['record'].get('time', 0),reverse=True)

How do I sort the above based on the "time" value? 如何根据“时间”值对以上内容进行排序?

Thanks. 谢谢。

Apparently, your structure is a string. 显然,您的结构是一个字符串。 You need to convert it to a python object using json.loads 您需要使用json.loads将其转换为python对象

import json

d = "[{'record': [{'id': '008', 'time': 1465689600}], 'price': '5.0', 'name': 'apple'}, {'record': [{'id': '002', 'time': 1465682600}], 'price': '9.0', 'name': 'banana'}]"

lines = json.loads(d)
sorted(lines, key=lambda k: k['record'][0].get('time', 0), reverse=True)
#                                       ^

Thereafter, the value at the key 'record' is a list. 此后,键'record'的值是一个列表。 The list has one dict object at index 0. So you need to access the dict object first, then you can access the values of the dictionary. 该列表在索引0处有一个dict对象。因此,您需要先访问dict对象,然后才能访问字典的值。

Since this is a json, I would just decode it using json.loads : 由于这是一个json,因此我将使用json.loads对其进行json.loads

import json

lines = '''
[{
    "name": "apple",
    "price": "5.0",
    "record": [
        {
            "id": "008",
            "time": 1465689600
        }
    ] 
},{
    "name": "banana",
    "price": "9.0",
    "record": [
        {
            "id": "002",
            "time": 1465682600
        }
    ]
}]
'''

d = json.loads(lines)

for x in sorted(d, key=lambda k: k['record'][0].get('time', 0), reverse=True):
    print x

Output: 输出:

{u'record': [{u'id': u'008', u'time': 1465689600}], u'price': u'5.0', u'name': u'apple'}
{u'record': [{u'id': u'002', u'time': 1465682600}], u'price': u'9.0', u'name': u'banana'}

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

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