import json


def to_json(data):
    """Return a JSON string representation of data.

    If data is a dictionary, None is replaced with 'null' in its keys and,
    recursively, in the keys of any dictionary it contains. This is done to
    allow the dictionary to be sorted by key before being written to JSON.

    """
    def none_to_null(obj):
        try:
            items = obj.items()
        except AttributeError:
            return obj
        # Don't make any ambiguities by requiring null to not be a key.
        assert 'null' not in obj
        return {'null' if key is None else key: none_to_null(val) for key, val in items}

    return json.dumps(none_to_null(data), indent=2, sort_keys=True)