Counting duplicate JSON keys in python

三世轮回 提交于 2021-02-10 06:25:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!