首先你需要重新格式化JSON数据,你在这里提供的包括一些错误。
为了回答这个问题,我使用了如下格式的JSON文件。
{
"logs" : [ {
"other" : "xVKNXCVNsk",
"time" : "2017-06-15T01:31:50.412Z",
"other2" : "xVKxXCbNsk",
"name" : "Alpha Beta: Bingo"
}, {
"other" : "xVKxXCbNsk",
"time" : "2017-06-15T01:31:37.229Z",
"other2" : "xVKxXCbNsk",
"name" : "Terra Zaba: Bingo"
}, {
"other" : "xVKxXCbNsk",
"time" : "2017-06-1T01:31:37.229Z",
"other2" : "xVKxXCbNsk",
"name" : "Terra Zaba: Bingo"
}]
}
格式化JSON文件后,我可以尝试回答这个问题。
import json
from pprint import pprint
PATH = r"E:\temp\temp.json"
def parse_func(f):
"""
parse the JSON file
:param f: the parsed file path
:return: the result dict
"""
parse_Dict = dict()
parse_List = list()
num_Dict = dict()
# load the JSON data to `data `
with open(f) as data_file:
data = json.load(data_file)
# parse the "name " and the "time "
for i in range(0, len(data["logs"])):
parse_List.append(data["logs"][i]["name"])
parse_List.append(data["logs"][i]["time"].split("T")[0])
print(parse_List)
# change the list to the dict
for ii in range(0, len(parse_List), 2):
# the "name " and the "time "
parse_Dict[parse_List[ii]] = parse_List[ii + 1]
# the "name " and the "retry number "
if parse_List[ii] not in num_Dict:
num_Dict[parse_List[ii]] = 1
else:
num_Dict[parse_List[ii]] = num_Dict[parse_List[ii]] + 1
print(parse_Dict)
print(num_Dict)
# format the result_Dict
result_Dict = dict()
for k in parse_Dict.keys():
result_Dict[k] = "%d for %s" % (num_Dict[k], parse_Dict[k])
print(result_Dict)
parse_func(PATH)
代码输出,
['Alpha Beta: Bingo', '2017-06-15', 'Terra Zaba: Bingo', '2017-06-15', 'Terra Zaba: Bingo', '2017-06-15']
{'Alpha Beta: Bingo': '2017-06-15', 'Terra Zaba: Bingo': '2017-06-15'}
{'Alpha Beta: Bingo': 1, 'Terra Zaba: Bingo': 2}
{'Alpha Beta: Bingo': '1 for 2017-06-15', 'Terra Zaba: Bingo': '2 for 2017-06-15'}
当写我发现了一个问题的代码,需要你自己判断。
因为dict()
中的按键需要唯一,所以当一个元素与name
相同时,却有不同的time
。如何记录。
例如,如果我更改了JSON文件。
{
"logs" : [ {
"other" : "xVKNXCVNsk",
"time" : "2017-06-15T01:31:50.412Z",
"other2" : "xVKxXCbNsk",
"name" : "Alpha Beta: Bingo"
}, {
"other" : "xVKxXCbNsk",
"time" : "2017-06-15T01:31:37.229Z",
"other2" : "xVKxXCbNsk",
"name" : "Terra Zaba: Bingo"
}, {
"other" : "xVKxXCbNsk",
"time" : "2016-06-1T01:31:37.229Z",
"other2" : "xVKxXCbNsk",
"name" : "Terra Zaba: Bingo"
}]
}
注意"time" : "2016-06-1T01:31:37.229Z",
线发生了变化。
输出将变为
['Alpha Beta: Bingo', '2017-06-15', 'Terra Zaba: Bingo', '2017-06-15', 'Terra Zaba: Bingo', '2016-06-1']
{'Terra Zaba: Bingo': '2016-06-1', 'Alpha Beta: Bingo': '2017-06-15'}
{'Terra Zaba: Bingo': 2, 'Alpha Beta: Bingo': 1}
{'Terra Zaba: Bingo': '2 for 2016-06-1', 'Alpha Beta: Bingo': '1 for 2017-06-15'}
注意请不同与上述一个。
你试过了什么?并修复你的JSON数据在你的问题它不是一个有效的JSON既不是有效的Python数据。 –
Thanks @ChihebNexus - JSON是从我接收它的应用程序自动输出的。我一定会按照您的有用建议来修复它。感谢您的投票。 – dpx
我没有downvote你的问题。无论你如何使用'json.loads()',它都会将你的JSON加载到python字典中。 –