Sort A Json Using Python
I am trying ot sort a JSON Object using Python. I have the following object : { 'text': 'hello world', 'predictions': [ {'class': 'Class 1', 'percentage': 4.63},
Solution 1:
You can use sorted
to sort the values, something like this :
json_obj = {
"text": "hello world",
"predictions":
[
{"class": "Class 1", "percentage": 4.63},
{"class": "Class 2", "percentage": 74.68},
{"class": "Class 3", "percentage": 9.38},
{"class": "Class 4", "percentage": 5.78},
{"class": "Class 5", "percentage": 5.53}
]
}
sorted_obj = dict(json_obj)
sorted_obj['predictions'] = sorted(json_obj['predictions'], key=lambda x : x['percentage'], reverse=True)
print(sorted_obj)
print(json_obj)
This will result in :
# The sorted values based on 'predictions' -> 'percentage'
{'predictions': [{'percentage': 74.68, 'class': 'Class 2'}, {'percentage': 9.38, 'class': 'Class 3'}, {'percentage': 5.78, 'class': 'Class 4'}, {'percentage': 5.53, 'class': 'Class 5'}, {'percentage': 4.63, 'class': 'Class 1'}], 'text': 'hello world'}
# The original json_obj will remain unchanged as we have created a new object sorted_obj from values of json_obj using dict()
{'text': 'hello world', 'predictions': [{'class': 'Class 1', 'percentage': 4.63}, {'class': 'Class 2', 'percentage': 74.68}, {'class': 'Class 3', 'percentage': 9.38}, {'class': 'Class 4', 'percentage': 5.78}, {'class': 'Class 5', 'percentage': 5.53}]}
Solution 2:
You are almost right, you probably want to create a copy of the dictionary and then replace predictions
's value to the sorted object. I'm assuming that you want to leave the original json_obj
unchanged, hence the deepcopy
(although it is unnecessary if we are simply doing a reassignment instead of in-place .sort
).
>>> json_obj = {
... "text": "hello world",
... "predictions":
... [
... {"class": "Class 1", "percentage": 4.63},
... {"class": "Class 2", "percentage": 74.68},
... {"class": "Class 3", "percentage": 9.38},
... {"class": "Class 4", "percentage": 5.78},
... {"class": "Class 5", "percentage": 5.53}
... ]
... }
>>> from copy import deepcopy
>>> sorted_json_obj = deepcopy(json_obj)
>>> sorted_json_obj['predictions'] = sorted(json_obj['predictions'], key=lambda k: k['percentage'], reverse=True)
>>> sorted_json_obj
{'predictions': [{'class': 'Class 2', 'percentage': 74.68},
{'class': 'Class 3', 'percentage': 9.38},
{'class': 'Class 4', 'percentage': 5.78},
{'class': 'Class 5', 'percentage': 5.53},
{'class': 'Class 1', 'percentage': 4.63}],
'text': 'hello world'}
Post a Comment for "Sort A Json Using Python"