python sort over list by value Json sctructure
I'm trying to get an output of a json file sorted by the following value "created_at" there a bit mass regarding all my tries in the code, I wasn't able to sort it.
If there is better solutions to resolve this task you more then welcome to share.
Your help and patience is much appreciated
import json
from datetime import datetime
import operator
from collections import OrderedDict
from operator import itemgetter
null = None
true = True
false = False
text = {
"Recipes":
[
{
"id": 2090210,
"user_id": 198555,
"parent_id": null,
"folder_id": 792876,
"version_no": 17,
"last_run_at": "2022-01-13T03:52:31.559455-08:00",
"created_at": "2022-01-13T00:53:48.433452-08:00",
"updated_at": "2022-01-13T03:52:27.798961-08:00",
"job_succeeded_count": 7,
"job_failed_count": 0,
"lifetime_task_count": 209,
"active": true
},
{
"id": 2072031,
"user_id": 198555,
"parent_id": null,
"folder_id": 283206,
"version_no": 98,
"last_run_at": "2022-01-04T05:14:41.485273-08:00",
"created_at": "2022-01-14T05:12:56.677338-08:00",
"updated_at": "2022-01-12T10:08:49.199488-08:00",
"job_succeeded_count": 1,
"job_failed_count": 0,
"lifetime_task_count": 227,
"active": false
},
]
}
#info = json.dump(text, sort_keys=False)
sorted_values = sorted(text.values())
#text.sort(key=lambda s: s['created_at'])
sorted_d = {r: text[r] for r in sorted(text, key=text.get('created_at'), reverse=True)}
#print(sorted_d)
ss = sorted(text.values()) #no recips
#print(ss)
newlist = sorted(ss, key=itemgetter(1))
print(newlist)
Solution 1:
No need to write extra lines just write this one line and it will sort you data
sorted_text = { "Recipes" : sorted(text['Recipes'], key=itemgetter('created_at'))}
print(sorted_text)