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’].

Here is what the json looks like simplified:

{'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. 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.

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.

Answer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *