-2

I have a JSON string that I want to sort. I want to sort it by the 'Name' field. I can't for the life of me find code that does this.

Unsorted:

{"RU": {"Name": "Russian", "TextDirection": "ltr"}, "FR": {"Name": "French", "TextDirection": "ltr"}, "AR": {"Name": "Arabic", "TextDirection": "rtl"}}

Sorted:

{"AR": {"Name": "Arabic", "TextDirection": "rtl"}, "FR": {"Name": "French", "TextDirection": "ltr"}, "RU": {"Name": "Russian", "TextDirection": "ltr"}}

Update:

As @jonrsharpe and @martineau pointed out. I needed to use an array or a list. I'm not too concerned about the structure. What was originally messing up the sort order was the conversion to json. By using an array instead, json did not muck with the sort order.

[{"Code": "AR", "Name": "Arabic", "TextDirection": "rtl"}, {"Code": "FR", "Name": "French", "TextDirection": "ltr"}, {"Code": "RU", "Name": "Russian", "TextDirection": "ltr"}]
Steve3p0
  • 2,332
  • 5
  • 22
  • 30

1 Answers1

1

You can user OrderedDict to implement a dictionary with ordered keys in Python.

However, you cannot guarantee that the JSON object will be loaded in order by other applications, because there is no ordering on dictionaries by nature (hashtables).

So, iterating on keys gives you no order guarantee, unless you use a specific class for both Python and JavaScript or if you put your dictionaries into an array whose order is static.

https://docs.python.org/3/library/collections.html#collections.OrderedDict

How do I sort a list of dictionaries by values of the dictionary in Python?

Fabien
  • 4,862
  • 2
  • 19
  • 33