David Schumann
David Schumann

Reputation: 14793

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. Still, executing JSON.parse(morgen) fails with

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.

Upvotes: 1

Views: 209

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55469

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.

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. However, that will produce a bytes object, so you need to decode it to make a text string. You can use the 'ASCII' codec for that. 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\\""}]}

Upvotes: 1

Pointy
Pointy

Reputation: 413702

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. (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:

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

Upvotes: 1

Related Questions