2013-07-10 83 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) 
相關問題