1

I'm learning how to use json with python and I wanted to know how to sort a json file alphabetically. Here is the file:

{
  "data": [
    {
      "text": "first sentence",
      "entities": [
      ]
    },
    {
      "text": "second sentence",
      "entities": [
      ]
    },
    {
      "text": "third sentence",
      "entities": [
      ]
    },
    {
      "text": "fourth sentence",
      "entities": [
      ]
    }
  ]
}

I would like the items in the data list to be in alphabetical order by the "text" key, and then to save that result into a new json file. Thank you for the help :)

  • 3
    Read the JSON into a dict/list, sort the list, write it back to JSON… – deceze Aug 07 '19 at 12:11
  • I think it's answered here: https://stackoverflow.com/questions/26924812/python-sort-list-of-json-by-value – Kostas Charitidis Aug 07 '19 at 12:17
  • there is not direct way to short your json shorting you need to add that all data in to Collection object and then you can short that after that that collection object convert to json Object or Json Array. – Amitsharma Aug 07 '19 at 12:50

1 Answers1

4

use sorted to sort by the text field

import json

with open('yourfile.json') as f:
    json_data = json.load(f)
    data_list = json_data['data']

json_data['data'] = sorted(data_list, key=lambda k: k['text'])

with open('newfile.json') as f:
    json.dump(json_data)