def flattenjson(obj, delim="__"):
    """
    Flattens a JSON object

    Arguments:
    obj -- dict or list, the object to be flattened
    delim -- string, delimiter for sub-fields

    Returns:
    The flattened JSON object
    """
    val = {}
    for i in obj:
        if isinstance(obj[i], dict):
            ret = flattenjson(obj[i], delim)
            for j in ret:
                val[i + delim + j] = ret[j]
        else:
            val[i] = obj[i]
    return val