2013-07-10 45 views
-1

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

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 
+2

那么,为什么你这样做你自己,而不是使用'JSON '模块? – zhangyangyu

+1

你为什么要这样做而不是使用内置的'json'库? –

+1

@zhangyangyu我在没有该库的服务器上使用旧版本的Python,我无法使用简单的JSON,因为我无法在其中安装任何东西。 – jcubic

回答

1

我发现我需要逃避所有的控制字符< 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) 
相关问题