import json
import ast


def flatten_json_1_level(event, field_name, field_name_underscore, dump_to_string):
    """ Flattens a JSON field 1 level. This function is used in flatten JSON

    :param event: A dictionary
    :param field_name: The field name to flatten
    :param field_name_underscore: The field name with an underscore appended
    :param dump_to_string: If true any remaining dictionaries will be converted to a string with json.dumps
    :return: An event with the field flattened

    Examples:

    .. code-block:: python

        # Example #1
        event = {'my_field': "{\"a\": None, \"b\"}"}
        event = flatten_json_1_level(event=input_event, field_name='my_field', field_name_underscore='my_field_', dump_to_string=True)
        output_event = {'my_field_a': None,
                        'my_field_b': 2}

    """

    # Load strings to JSON when possible, otherwise return the event
    if type(event[field_name]) is not dict:
        try:
            event[field_name] = json.loads(event[field_name])
        except:
            try:
                event[field_name] = ast.literal_eval(event[field_name])
            except:
                return event

    # iterate through the dictionary and flatten a single level
    try:
        for k, v in event[field_name].items():
            if type(v) is dict and dump_to_string:
                event[field_name_underscore + k.lower()] = json.dumps(v)
            else:
                event[field_name_underscore + k.lower()] = v

        del event[field_name]

    except:
        return event

    return event