Home > Software design >  How to sort JSON objects of arrays in python?
How to sort JSON objects of arrays in python?

Time:05-31

I want to sort a JSON object of arrays on the basis of the key "score". Here's a sample data:

[
    {
        "name": "Hilary Carr",
        "submissions": [
            {
                "name": "Laudantium deleniti beatae fuga.",
                "date": "05/12/2021",
                "score": 37
            }
        ]
    },
{
        "name": "Frederick Williamson",
        "submissions": [
            {
                "name": "Expedita architecto voluptas autem veniam.",
                "date": "03/05/2009",
                "score": 47
            },
            {
                "name": "Animi facere excepturi.",
                "date": "01/02/2021",
                "score": 100
            }
        ]
    }
]

Sample output:

[
    {
        "name": "Hilary Carr",
        "submissions": [
            {
                "name": "Laudantium deleniti beatae fuga.",
                "date": "05/12/2021",
                "score": 37
            }
        ]
    },
{
        "name": "Frederick Williamson",
        "submissions": [
            {
                "name": "Animi facere excepturi.",
                "date": "01/02/2021",
                "score": 100
            },
            {
                "name": "Expedita architecto voluptas autem veniam.",
                "date": "03/05/2009",
                "score": 47
            }
        ]
    }
]

I tried the solution given in this question Sort a JSON using Python, but my JSON data is mutilated by this. Here's what I tried:

for i in range(len(inputData)):
    sample_data_sort = dict(inputData)
    sample_data_sort = sorted(inputData[i]['submissions'], key=lambda x : x['score'], reverse=True)
    print(sample_data_sort)

Output that I get:

[
  {
   "name": "Laudantium deleniti beatae fuga.",
   "date": "05/12/2021",
   "score": 37
   }
],
[
 {
 "name": "Animi facere excepturi.",
 "date": "01/02/2021",
 "score": 100
 },
 {
  "name": "Expedita architecto voluptas autem veniam.",
  "date": "03/05/2009",
  "score": 47
 }
]

As you can see, I get the mutilated JSON back. Can you please give some tips to rectify this problem, so that the output that I get is similar to the input?

CodePudding user response:

Python Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

If you are allowed to modify the origin JSON Object.

Just do like this:


def sort_submissions_of_items(json_list):
    for item in json_list:
        subs = item.get("submissions", [])
        if isinstance(subs, list):
            subs.sort(key=lambda x: x.get("score", 0), reverse=True)

sort_submissions_of_items(inputData)

CodePudding user response:

Try this
Just sort the internal dictionaries and then combine them by list derivation
And the original structure of the data will be guaranteed

a = [
    {
        "name": "Hilary Carr",
        "submissions": [
            {
                "name": "Laudantium deleniti beatae fuga.",
                "date": "05/12/2021",
                "score": 37
            }
        ]
    },
    {
        "name": "Frederick Williamson",
        "submissions": [
            {
                "name": "Expedita architecto voluptas autem veniam.",
                "date": "03/05/2009",
                "score": 47
            },
            {
                "name": "Animi facere excepturi.",
                "date": "01/02/2021",
                "score": 100
            }
        ]
    }
]


result = [
    {
        "name": i["name"],
        "submissions": sorted(i["submissions"], key=lambda x: x["score"], reverse=True)
    }
    for i in a
]
print(result)


output

[{'name': 'Hilary Carr', 'submissions': [{'name': 'Laudantium deleniti beatae fuga.', 'date': '05/12/2021', 'score': 37}]}, {'name': 'Frederick Williamson', 'submissions': [{'name': 'Animi facere excepturi.', 'date': '01/02/2021', 'score': 100}, {'name': 'Expedita architecto voluptas autem veniam.', 'date': '03/05/2009', 'score': 47}]}]

CodePudding user response:

The key is in this piece of code

...sorted(inputData[i]['submissions']...

You are not sorting your full data. Instead what you are doing is:

  1. You take each element in your original array (with inputData[i])
  2. You are picking out only the submissions field
  3. You sort the submissions array based on the value score

The solution you want is probably something like this

outputData = [{**i, 'submissions': sorted(i['submissions'], key= lambda j: j['score'], reverse=True)} for i in inputData]

I recommend reading through it and comparing it with your original solution :D

  • Related