-5

Lets say I have a JSON file like below:

{
    "data": [
        {
            "id": 2,
            "name": "fork"
        },
        {
            "id": 1,
            "name": "knife"
        },
        {
            "id": 3,
            "name": "spoon"
        }
    ]
}

I am unsure how I sort the data inside data[] so it would be something like below (the id and name sorted by least to greatest). I tried a sorted() function but I am completely unsure how this would work.

{
    "data": [
        {
            "id": 1,
            "name": "knife"
        },
        {
            "id": 2,
            "name": "fork"
        },
        {
            "id": 3,
            "name": "spoon"
        }
    ]
}

2 Answers2

1

You can use key parameter:

dct = { "data": [ { "id": 2, "name": "fork" }, { "id": 1, "name": "knife" }, { "id": 3, "name": "spoon" } ] }

output = {'data': sorted(dct['data'], key=lambda d: d['id'])}

print(output) # {'data': [{'id': 1, 'name': 'knife'}, {'id': 2, 'name': 'fork'}, {'id': 3, 'name': 'spoon'}]}
j1-lee
  • 13,764
  • 3
  • 14
  • 26
1

You need to sort by id

sorted(data, key=lambda x: x['id'])

Benoît P
  • 3,179
  • 13
  • 31