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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like