Sort a JSON using Python -
i trying ot sort json object using python.
i have 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 want have 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, want order array of objects percentage.
i have tried command :
sorted_obj = sorted(json_obj['predictions'], key=lambda k: k['percentage'], reverse=true)
and had error :
traceback (most recent call last): file "<stdin>", line 1, in <module> typeerror: string indices must integers
any needed,
thanks
you can use sorted
sort values, :
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 result in :
# 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'} # original json_obj remain unchanged have created new object sorted_obj 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}]}
Comments
Post a Comment