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},
{"class": "Class 2", "percentage": 74.68},
{"class": "Class 3", "percentage": 9.38},
{"class": "Class 4", "percentage": 5.78},
{"class": "Class 5", "percentage": 5.53}
]
}
And I want to have this object instead :
{
"text": "hello world",
"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}
]
}
In fact, I want to order my array of objects by percentage.
I have tried this command :
sorted_obj = sorted(json_obj['predictions'], key=lambda k: k['percentage'], reverse=True)
And I had this error :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
Any help is needed,
Thanks
You cannot sort a JSON string.. JSON is an Object Notation for data transport - ie, a string. You will have to evaluate it as an object literal (e.g. with eval) and make any changes you want before reserializing it.
One option might be to make your data look like this: var json = [{ "name": "user1", "id": 3 }, { "name": "user2", "id": 6 }, { "name": "user3", "id": 1 }]; Now you have an array of objects, and we can sort it. Show activity on this post.
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}]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With