简体   繁体   English

如何根据密钥对类型 python 对我的 json 数据进行排序

[英]How can I sort my json data based off of a key pair type python

The Problem:问题:

I am simply trying to find a way to sort my json data by ['logonTime'].我只是想找到一种方法来按 ['logonTime'] 对我的 json 数据进行排序。

Here is what the json looks like simplified:这是 json 的简化外观:

{'results': 
          [{'userName': 'PDD1\\Samantha', 
            'logonTime': 1615222801000.0, 
             'deviceId': 892}] 
}

I want all the entries to sort by ['logonTime'] but I haven't found a correct way to do so.我希望所有条目都按 ['logonTime'] 排序,但我还没有找到正确的方法。 I think the reason this is hard for me is because there seems to be so many different ways to do it.我认为这对我来说很难的原因是因为似乎有很多不同的方法可以做到这一点。

I tried the method from this link here Sort a JSON using Python however I got an error saying cannot assign to lambda when I tried to make the code myself.我在此处尝试了此链接中的方法Sort a JSON using Python但是当我尝试自己编写代码时,我收到一条错误cannot assign to lambda

Here is the code nomrally:这是通常的代码:

#client file that handles the api get request. py
def get_logged_on_users(self):
        resp = self.api_get_request(self.NINJA_API_GET_LOGGED_ON_USERS)
        if not resp.status_code == self.STATUS_OK:
            return False
        return resp.json()


#main file.py
napi = ninjarmm_api.client(ninjaapi, ninjasak, iseu=False, debug=False)
napialert = napi.get_disks()
napilousers = napi.get_logged_on_users()
napidevices = napi.get_devices()
print(napilousers)

Here is my terrible attempt at trying to sort the data from the link I saw before:这是我尝试从之前看到的链接中对数据进行排序的糟糕尝试:

sorted_napilousers = dict(napilousers)
sorted_napilousers['results'] = sorted(napilousers)['logonTime'], key=lambda x : x['logonTime'], reverse=True)
print(sorted_napilousers)

#this results in "cannot assign to lambda" when ran

Any ideas or suggestions I can try out?我可以尝试任何想法或建议吗? I feel like its something simple here with the sort options or maybe a json.dumps option but I have seen to many options and it kinda confused me.我觉得这里的排序选项很简单,或者可能是 json.dumps 选项,但我见过很多选项,这让我有点困惑。

Here is a fix for your code, try it:这是您的代码的修复程序,请尝试:

napilousers = {'results': 
          [{'userName': 'PDD1\\Samantha', 
            'logonTime': 111111.0, 
            'deviceId': 892},
             {'userName': 'PDD1\\Samantha', 
            'logonTime': 333333.0, 
            'deviceId': 892},{'userName': 'PDD1\\Samantha', 
            'logonTime': 222222.0, 
            'deviceId': 892}] 
             
}

sorted_napilousers = dict(napilousers)
sorted_napilousers['results'] = sorted(napilousers['results'], key=lambda x : x['logonTime'], reverse=True)
print(sorted_napilousers)

your attempt is not terrible, you just made some small mistakes.你的尝试并不可怕,你只是犯了一些小错误。

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

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