import json


def merge_jsons_single_level(filenames):
    """ Merge a list of toplevel-dict json files.
        Union dicts at the first level.
        Raise exception when duplicate keys encountered.
        Returns the merged dict.
    """

    merged = {}
    for filename in filenames:
        with open(filename) as f:
            d = json.load(f)

            for key, value in d.iteritems():
                if key not in merged:
                    merged[key] = value
                    continue

                # Handle pre-existing keys
                if merged[key] == value:
                    pass
                elif type(value) == dict and type(merged[key]) == dict:
                    merged[key].update(value)
                else:
                    raise ValueError("No merge strategy for key %s, value of type %s, from %s into %s" % (str(key),
                                                                                                          str(type(value)),
                                                                                                          str(value),
                                                                                                          str(merged[key])))
    return merged