[英]string produced by pythons json.dumps() errors when loading with javascripts JSON.parse() at escaped double quotes
I have the following string with two escaped doublequotes: 我有以下带有两个转义双引号的字符串:
var morgen = '{"a": [{"title": "Fotoausstellung \"Berlin, Berlin\""]}';
This is valid JSON as far as I know. 据我所知,这是有效的JSON。 Still, executing JSON.parse(morgen)
fails with 尽管如此,执行JSON.parse(morgen)
仍然失败
SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 36 of the JSON data
The string was produced by pythons json.dumps()
method. 该字符串是由json.dumps()
方法产生的。
You'll have to double the backslash characters: 您必须将反斜杠字符加倍:
var morgen = '{"a": [{"title": "Fotoausstellung \\"Berlin, Berlin\\""]}';
That is necessary because JavaScript will remove the single backslashes when it parses the overall string constant. 这是必需的,因为JavaScript在解析整个字符串常量时将删除单个反斜杠。 (The \\"
pair in a string constant is interpreted as meaning a single "
character.) (字符串常量中的“ \\"
对被解释为表示单个"
字符。)
If all you want is that structure as a JavaScript object, you'd just do this: 如果您想要的只是将该结构作为JavaScript对象,则只需执行以下操作:
var morgen = {"a": [{"title": "Fotoausstellung \"Berlin, Berlin\""]};
As Pointy mentions, you should be able to just embed that JSON as an object in your JavaScript source, rather than as a string which has to be parsed. 正如Pointy提到的那样,您应该能够将JSON作为对象嵌入到JavaScript源中,而不是作为必须解析的字符串。
However, to print that JSON with escape codes suitable for use as a JavaScript string you can tell Python to encode it with the 'unicode-literal' codec. 但是,要打印带有适合用作JavaScript字符串的转义码的JSON,可以告诉Python使用“ unicode-literal”编解码器对其进行编码。 However, that will produce a bytes
object, so you need to decode it to make a text string. 但是,这将产生一个bytes
对象,因此您需要对其进行解码以生成文本字符串。 You can use the 'ASCII' codec for that. 您可以为此使用“ ASCII”编解码器。 Eg, 例如,
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'))
output 产量
{'a': [{'title': 'Fotoausstellung "Berlin, Berlin"'}]}
b'{"a": [{"title": "Fotoausstellung \\\\"Berlin, Berlin\\\\""}]}'
{"a": [{"title": "Fotoausstellung \\"Berlin, Berlin\\""}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.