当使用javascripts JSON.parse()以双引号引起来时加载时,pythons json.dumps()错误产生的字符串

大卫·舒曼

我有以下带有两个转义双引号的字符串:

var morgen = '{"a": [{"title": "Fotoausstellung \"Berlin, Berlin\""]}';

据我所知,这是有效的JSON。尽管如此,执行JSON.parse(morgen)失败并

SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 36 of the JSON data

该字符串是通过pythonsjson.dumps()方法生成的

2号环

正如Pointy提到的那样,您应该能够将JSON作为对象嵌入到JavaScript源中,而不是作为必须解析的字符串。

但是,要打印带有适合用作JavaScript字符串的转义码的JSON,您可以告诉Python使用“ unicode-literal”编解码器对其进行编码。但是,这将产生一个bytes对象,因此您需要对其进行解码以生成文本字符串。您可以为此使用“ ASCII”编解码器。例如,

import json

# The problem JSON using Python's raw string syntax
s = r'{"a": [{"title": "Fotoausstellung \"Berlin, Berlin\""}]}'

# Convert the JSON string to a Python object
d = json.loads(s)
print(d)

# Convert back to JSON, with escape codes.
json_bytes = json.dumps(d).encode('unicode-escape')
print(json_bytes)

# Convert the bytes to text
print(json_bytes.decode('ascii'))    

输出

{'a': [{'title': 'Fotoausstellung "Berlin, Berlin"'}]}
b'{"a": [{"title": "Fotoausstellung \\\\"Berlin, Berlin\\\\""}]}'
{"a": [{"title": "Fotoausstellung \\"Berlin, Berlin\\""}]}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章