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'".
32 Answers
There are several steps:
- Read the file using json.load()
- Sort the list of objects using list.sort()
- Use a key-function to specify the sort field.
- Use operator.itemgetter() to extract the field of interest
- Write the data with json.dump()
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")