Skip to content Skip to sidebar Skip to footer

Counting Duplicate Json Keys In Python

I have a JSON file with multiple duplicate keys in the following format: 'data': { 'nameA': { 'result': someInt, 'timestamp': 'someTime' }, 'nameB': {

Solution 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()
    fork, 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)

forkeyin parsed['data'][0]:
    print("Key: {} | Count: {}".format(key, len(parsed['data'][0][key])))

Output:

Key:key2|Count:1Key:key1|Count:2

Post a Comment for "Counting Duplicate Json Keys In Python"