-1

I'm trying to parse a json file which looks something like this:

{ "my_test":[
    { "group_name":"group-A", "results": [
        { "test_name": "test1", "time": "8.556", "status": "pass" },
        { "test_name": "test2", "time": "45.909", "status": "pass" },
        { "test_name": "test3", "time": "9.383", "status": "fail" },
        ...
    }
}

how can I print out the test results in ascending order? (by the name or by time)

EDIT: The output could be in ascending order of time:

test1 8.556
test3 9.383
test2 45.909
Oisin
  • 770
  • 8
  • 22
tsf144
  • 817
  • 1
  • 8
  • 14

2 Answers2

2

You could try this, using the builtin sorted function.

from json import loads

json_data = """{
    "my_test": [{
        "group_name": "group-A",
        "results": [{
            "test_name": "test1",
            "time": "8.556",
            "status": "pass"
        }, {
            "test_name": "test2",
            "time": "45.909",
            "status": "pass"
        }, {
            "test_name": "test3",
            "time": "9.383",
            "status": "fail"
        }]
    }]
}"""

data = loads(json_data)

for group in data["my_test"]:
    print group["group_name"]
    sorted_results = sorted(group["results"], key=lambda a: float(a["time"]))
    for result in sorted_results:
        print(result["test_name"] + ": " + result["time"])
jacob
  • 4,656
  • 1
  • 23
  • 32
0

Have you looked here: How do I sort a list of dictionaries by values of the dictionary in Python?

Just extract your list of dictionaries with list_of_dicts = your_dict_name['results']

then

import operator

and follow the instructions by vemury for example. " To sort the list of dictionaries by key='name':

list_of_dicts.sort(key=operator.itemgetter('name'))

To sort the list of dictionaries by key='age':

list_of_dicts.sort(key=operator.itemgetter('age')) " by vemury

Community
  • 1
  • 1
Leo Skhrnkv
  • 1,513
  • 16
  • 27