问题
I have a JSON file with multiple duplicate keys in the following format:
"data": {
"nameA": {
"result": someInt,
"timestamp": "someTime"
},
"nameB": {
"result": someInt,
"timestamp": "someTime"
},
"nameA": {
"result": someInt,
"timestamp": "someTime"
},
"nameC": {
"result": someInt,
"timestamp": "someTime"
}
}
I need to dynamically determine the number of instances of each key and print them out. What would be the best way to accomplish this for a JSON in this format?
回答1:
Based upon the answer given to this question: json.loads allows duplicate keys in a dictionary, overwriting the first value , this should work:
import json
testjson = '{"data": {"key1": "val", "key2": "val", "key1": "val"}}'
def parse_multimap(ordered_pairs):
multimap = dict()
for k, v in ordered_pairs:
if k in multimap:
multimap[k].append(v)
else:
multimap[k] = [v]
return multimap
parsed = json.loads(testjson, object_pairs_hook=parse_multimap)
for key in parsed['data'][0]:
print("Key: {} | Count: {}".format(key, len(parsed['data'][0][key])))
Output:
Key: key2 | Count: 1
Key: key1 | Count: 2
来源:https://stackoverflow.com/questions/51878706/counting-duplicate-json-keys-in-python