我有一个带有多个重复键的JSON文件,格式如下:
ssh-keyscan -t rsa "$EI_CI_HOST" >> ~/.ssh/known_hosts
我需要动态确定每个键的实例数量并打印出来。对于这种格式的JSON,完成此操作的最佳方法是什么?
答案 0 :(得分:1)
基于对这个问题的回答:json.loads allows duplicate keys in a dictionary, overwriting the first value,这应该可以工作:
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])))
输出:
Key: key2 | Count: 1
Key: key1 | Count: 2