Sorting a Json File by a Certain Key

I am coding in Python.

I have a carV.json file with content

{"CarValue": "59", "ID": "100043" ...}
{"CarValue": "59", "ID": "100013" ...}
...

How can I sort the file content into

{"CarValue": "59", "ID": "100013" ...}
{"CarValue": "59", "ID": "100043" ...}
...

using the "ID" key to sort?

I tried different methods to read and perform the sort, but always ended up getting errors like "no sort attribute" or ' "unicode' object has no attribute 'sort'".

3

2 Answers

There are several steps:

Here's some code to get you started:

import json, operator

s = '''\
[
  {"CarValue": "59", "ID": "100043"},
  {"CarValue": "59", "ID": "100013"}
]
'''

data = json.loads(s)
data.sort(key=operator.itemgetter('ID'))
print(json.dumps(data, indent=2))

This outputs:

[
  {
    "CarValue": "59",
    "ID": "100013"
  },
  {
    "CarValue": "59",
    "ID": "100043"
  }
]

For your application, open the input file and use json.load() instead of json.loads(). Likewise, open a output file and use json.dump() instead of json.dumps(). You can drop the indent parameter as well, that is just to make the output look nicely formatted.

simple and probably faster in case of large data - pandas.DataFrame.to_json

>>> import pandas as pd
>>> unsorted = pd.read_json("test.json")
>>> (unsorted.sort_values("ID")).to_json("sorted_test.json")
>>> sorted = unsorted.sort_values("ID")
>>> sorted
   CarValue      ID
1        59  100013
0        59  100043
>>> sorted.to_json("n.JSON")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest