Javascript JSON.parse需要转义哪些字符
我注意到,您无法在json中为json保存Javascript JSON.parse需要转义哪些字符,javascript,python,json,parsing,escaping,Javascript,Python,Json,Parsing,Escaping,我注意到,您无法在json中为json保存1B(转义)。解析函数将获得SyntaxError:Unexpected token(在google chrome中)您需要将其编写为Unicode\u001b。我想用Python编写json_序列化函数,字符串中还有哪些字符需要转义?这是我的python函数 def json_serialize(obj): result = '' t = type(obj) if t == types.StringType: r
1B
(转义)。解析函数将获得SyntaxError:Unexpected token
(在google chrome中)您需要将其编写为Unicode\u001b
。我想用Python编写json_序列化函数,字符串中还有哪些字符需要转义?这是我的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
我发现我需要转义所有小于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)
def转义(str):
str=str.replace('\\','\\\').replace(''''','\\').replace('\n','\\n')。
替换('\t','\\t')
结果=[]
对于CHIN str:
n=ord(ch)
如果n<32:
h=十六进制(n)。替换('0x','')
结果+=['\\u%s%s'('0'*(4-len(h)),h)]
其他:
结果+=[ch]
返回“”。加入(结果)
那么,为什么你要自己做而不是使用json
模块?为什么你要这样做而不是使用内置的json
库?@zhangyangyu我在没有库的服务器上使用旧版本的Python,我不能使用简单的json,因为我不能在那里安装任何东西。多么糟糕的情况啊!:(@jcubic