views:

164

answers:

1

Hi! Im programming with django and i need to serialize an object to a string, but i need to get the string \/ serialized.

An example:

simplejson.dumps({'id' : 'root\/leaf'})

I need an output like this:

'{"id": "root\/leaf"}'

but i get this:

'{"id": "root\\\\leaf"}'

Thank you!!

PD: Sorry for my english :-P

+1  A: 

JSON requires that the literal \ character be escaped, and represented as \\. Python also represents the literal \ character escaped, as \\. Between the two of them, \ becomes \\\\.

Notice the following in Python:

>>> "\\/" == "\/"
True

>>> {"id": "root\/leaf"} == {"id": "root\\/leaf"}
True

>>> {"id": "root\\/leaf"}["id"]
'root\\/leaf'

>>> print {"id": "root\\/leaf"}["id"]
root\/leaf 

Python is printing the extra escape . So when you do simplejson.dumps({"id": "root\/leaf"}), python is printing the correct result {'id': 'root\\/leaf'}, but with the extra Python escapes, hence {'id': 'root\\\\/leaf'}. Python regards each \\ as a single character. If you write to a file instead of a string, you'll get {'id': 'root\\/leaf'}.

Edit: I might add, the literal JSON {"id": "root\/leaf"} would decode to {'id': 'root/leaf'}, as the literal JSON \/ maps to the / character. Both \/ and / are valid JSON encodings of /; there doesn't seem to be an easy way to make simplejson use \/ instead of / to encode /.