0

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'".

nbro
  • 15,395
  • 32
  • 113
  • 196
yong
  • 31
  • 1
  • 1
  • 4
  • 2
    How about you post things you tried and we will guide you further? – MaLiN2223 Jul 23 '17 at 15:28
  • 2
    Json is basically a quasi-dictionary and in python you are playing with the data in dict format. instead of asking a new question, look up and research existing questions about dictionary sorting. –  Jul 23 '17 at 15:28
  • post the full path to your "leaf" objects (extended json) – RomanPerekhrest Jul 23 '17 at 15:29

2 Answers2

7

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.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
3

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")
Saket Mittal
  • 3,726
  • 3
  • 29
  • 49