Skip to content Skip to sidebar Skip to footer

Json In Python: Receive/check Duplicate Key Error

The json module of python acts a little of the specification when having duplicate keys in a map: import json >>> json.loads('{'a': 'First', 'a': 'Second'}') {u'a': u'Seco

Solution 1:

Well, you could try using the JSONDecoder class and specifying a custom object_pairs_hook, which will receive the duplicates before they would get deduped.

import json

defdupe_checking_hook(pairs):
    result = dict()
    for key,val in pairs:
        if key in result:
            raise KeyError("Duplicate key specified: %s" % key)
        result[key] = val
    return result

decoder = json.JSONDecoder(object_pairs_hook=dupe_checking_hook)

# Raises a KeyError
some_json = decoder.decode('''{"a":"hi","a":"bye"}''')

# works
some_json = decoder.decode('''{"a":"hi","b":"bye"}''')

Solution 2:

The below code will take any json that has repeated keys and put them into an array. for example takes this json string '''{"a":"hi","a":"bye"}''' and gives {"a":['hi','bye']} as output

import json
defdupe_checking_hook(pairs):
    result = dict()
    for key,val in pairs:
        if key in result:
            if(type(result[key]) == dict):
                temp = []
                temp.append(result[key])
                temp.append(val)
                result[key] = temp
            else:
                result[key].append(val)
        else:
            result[key] = val
    return result

decoder = json.JSONDecoder(object_pairs_hook=dupe_checking_hook)
#it will not raise error
some_json = decoder.decode('''{"a":"hi","a":"bye"}''')

Post a Comment for "Json In Python: Receive/check Duplicate Key Error"