简体   繁体   English

在python中排序多维JSON对象

[英]Sorting multidimensional JSON objects in python

I have an object as such and want to sort it by time (line first, point second) in each dimension (simplified json): 我有一个这样的对象,想在每个维度(简化的json)中按时间(第一行,第二点)进行排序:

[{
    "type":"point"
},
{
    "type":"line",
    "children": [
        {
            "type":"point"
        },
        {
            "type":"point"
        },
        {
            "type":"line"
        }
    ]

},
{
    "type":"point"     
}]

This dimention could be deeper and have much more points/lines within each other. 这种尺寸可能更深 ,彼此之间具有更多的点/线。

The sorted output would be something like this: 排序后的输出将如下所示:

[{
    "type":"line",
    "children": [
        {
            "type":"line"
        },
        {
            "type":"point"
        },
        {
            "type":"point"
        }
    ]

},
{
    "type":"point"
},
{
    "type":"point"     
}]

Thanks 谢谢

You'd need to process this recursively: 您需要递归处理:

from operator import itemgetter

def sortLinesPoints(data):
    if isinstance(data, dict):
        if 'children' in data:
            sortLinesPoints(data['children'])
    else:
        for elem in data:
            sortLinesPoints(elem)
        data.sort(key=itemgetter('type'))

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

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