0

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?

1
  • 1
    You probably wanted in-place sort instead, i.e. inputData[i]['submissions'].sort(key=lambda x : x['score'], reverse=True)) Commented May 31, 2022 at 2:06

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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}]}]

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.