Home > Software engineering >  Sort JSON data based on a specific word in a property of an object
Sort JSON data based on a specific word in a property of an object

Time:05-06

I want sort data from a json file.

I have following data.json json File content: Each package is a object with two properties.

{
    "attr_2.4.48": {
      "exposed": false,
      "score": "Not qualified"
    },
    "cockpit_218": {
      "exposed": false,
      "score": "partial qualified"
    },
    "base-passwd_3.5.29": {
        "exposed": false,
        "score": "Qualified"
    },
    "audit_2.8.5": {
      "exposed": true,
      "score": "partial qualified"
    },
    "base-files_3.0.14": {
      "exposed": false,
      "score": "Not qualified"
    }
}

The output should be sorted in following way:

  • first all packages with "score": "Not qualified"

  • second all packages with "score": "partial qualified"

  • and last all packages with "score": "Qualified"

Each package with the same score should also be sorted alphabetically

The sorted data should look like this:

{
    "attr_2.4.48": {
        "exposed": false,
        "score": "Not qualified"
    },
    "base-files_3.0.14": {
        "exposed": false,
        "score": "Not qualified"
    },
    "audit_2.8.5": {
        "exposed": true,
        "score": "partial qualified"
    },
    "cockpit_218": {
        "exposed": false,
        "score": "partial qualified"
    },
    "base-passwd_3.5.29": {
        "exposed": false,
        "score": "Qualified"
    }
}

My problem at the moment is, that i don't know how to sort the data based on the socre value.

My code is only sorting the packages by score value in alphabetical order:

with open(data.json, 'r', encoding='utf-8') as json_file:
     json_content = json.load(json_file)

package = content.keys()
sorted_content = sorted(package, key=lambda ip: content[ip]['score'], reverse=False)

How can I update my code so that the data looks like the output shown above?

CodePudding user response:

If json_content is your parsed json file you can do:

from collections import OrderedDict

order = ["Not qualified", "partial qualified", "Qualified"]

json_content = OrderedDict(
    sorted(
        json_content.items(), key=lambda i: (order.index(i[1]["score"]), i[0])
    )
)

print(json.dumps(json_content, indent=4, sort_keys=False))

Prints:

{
    "attr_2.4.48": {
        "exposed": false,
        "score": "Not qualified"
    },
    "base-files_3.0.14": {
        "exposed": false,
        "score": "Not qualified"
    },
    "audit_2.8.5": {
        "exposed": true,
        "score": "partial qualified"
    },
    "cockpit_218": {
        "exposed": false,
        "score": "partial qualified"
    },
    "base-passwd_3.5.29": {
        "exposed": false,
        "score": "Qualified"
    }
}
  • Related