quote_swap = functools.partial(string.translate, table=string.maketrans(
    '\'"', '"\''))

def encode_single_quoted_js_string(s):
    return quote_swap(json.dumps(quote_swap(s)))
Escaping JavaScript Strings in Python