我试图解析一个看起来像这样的json文件:
{ "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" },
...
}
}
如何按升序打印出测试结果? (按名称或时间)
编辑: 输出可以按时间升序排列:
test1 8.556
test3 9.383
test2 45.909
答案 0 :(得分:2)
您可以使用内置sorted
函数尝试此操作。
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"])
答案 1 :(得分:0)
你看过这里: How do I sort a list of dictionaries by values of the dictionary in Python?
只需提取您的词典列表即可 list_of_dicts = your_dict_name ['结果']
然后
import operator
并按照vemury的说明进行操作。 " 要按键=' name':
对词典列表进行排序list_of_dicts.sort(键= operator.itemgetter('名称'))
按键=' age'
对字典列表进行排序list_of_dicts.sort(键= operator.itemgetter('年龄')) " 由vemury