0

我注意到你不能1B在 json 中为 JSON.parse 函数保存(转义)你会得到SyntaxError: Unexpected token(在谷歌浏览器中)你需要把它写成 unicde \u001b。我在 Python 中有 json_serialize 函数,我需要转义字符串中的哪些其他字符?这是我的python函数

def json_serialize(obj):
    result = ''
    t = type(obj)
    if t == types.StringType:
        result += '"%s"' % obj.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n').replace('\t', '\\t')
    elif t == types.NoneType:
        result += 'null'
    elif t == types.IntType or t == types.FloatType:
        result += str(obj)
    elif t == types.LongType:
        result += str(int(obj))
    elif t == types.TupleType:
        result += '[' + ','.join(map(json_serialize, list(obj))) + ']'
    elif t == types.ListType:
        result += '[' + ','.join(map(json_serialize, obj)) + ']'
    elif t == types.DictType:
        array = ['"%s":%s' % (k,json_serialize(v)) for k,v in obj.iteritems()]
        result += '{' + ','.join(array) + '}'
    else:
        result += '"unknown type - ' + type(obj).__name__ + '"'
    return result
4

1 回答 1

2

我发现我需要转义所有< 32的控制字符。这是我的转义函数:

def escape(str):
    str = str.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n').
        replace('\t', '\\t')
    result = []
    for ch in str:
        n = ord(ch)
        if n < 32:
            h = hex(n).replace('0x', '')
            result += ['\\u%s%s' % ('0'*(4-len(h)), h)]
        else:
            result += [ch]
    return ''.join(result)
于 2013-07-10T07:36:19.763 回答