开发者

Simplejson dumps char \

开发者 https://www.devze.com 2022-12-29 15:01 出处:网络
I\'m programming with Django need to serialize an object to a string, but I need to get the string \\/ serialized.

I'm programming with Django 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"}


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 /.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号