-1

I need to sort my JSON based on value in ascending/descending order in PYTHON

This is my JSON:

{
    "efg": 1,
    "mnp": 4,
    "xyz": 3
}

expected output is :

{
    "mnp": 4,
    "xyz": 3,
    "efg": 1,
}

The above is just a sample JSON, Actual JSON is much bigger

And how to reverse sort it based on value

{
    "efg": 1,
    "xyz": 3,
    "mnp": 4

}

Please help

-Ashish

Ashish
  • 479
  • 3
  • 7
  • 18
  • Convert json to python dict, then sort it https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – MjZac Apr 17 '20 at 13:00
  • 2
    Does this answer your question? [Items in JSON object are out of order using "json.dumps"?](https://stackoverflow.com/questions/10844064/items-in-json-object-are-out-of-order-using-json-dumps) – metatoaster Apr 17 '20 at 13:01

1 Answers1

0
import json
from collections import OrderedDict


json_str = """
{
    "efg": 1,
    "mnp": 4,
    "xyz": 3
}
"""
json_dict = json.loads(json_str)
dict_sorted = OrderedDict(sorted(json_dict.items(), key=lambda x: x[1]))
str_sorted = json.dumps(dict_sorted) #  '{"efg": 1, "xyz": 3, "mnp": 4}'
MjZac
  • 3,476
  • 1
  • 17
  • 28