-1

I have a dictionary:

data = {"data": "\u512b"}

while I dump that to json:

import json
print json.dumps(data)

I got:{"a":"\\u512b"} What should I do to get exactly {"a":"\u512b"}?

NOTE: I try to add u before the string so it becomes u'\u512b' and the extra \ won't show up again, please also tell me why

PeterLai
  • 105
  • 1
  • 9

2 Answers2

0

You can do some hacking.

import json

data = {"data": "\u512b"}
s = json.dumps(data)
print(s.replace(r'\u', 'u'))
print(type(s.replace(r'\u', 'u')))

Output:

{"data": "\u512b"}
<type 'str'>
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
0

My guess is that you are just confused by the output of the Python interpreter, displaying you the json.dumps generated string with its own \ escape character prepended to the \ character in the string. The JSON string as a value contains exactly one \, as you want (IIUC):

>>> data = {"data": "\u512b"}
>>> data
{'data': '\u512b'}
>>> import json
>>> json.dumps(data)
'{"data": "\\u512b"}'
>>> print(json.dumps(data))
{"data": "\u512b"}
>>> json.dump(data, open('data.json', 'w'))
>>> ^Z
C:\opt\Console2>type data.json
{"data": "\u512b"}

This is entirely independent of JSON in fact, as the following example shows:

>>> s = "s\\u"
>>> s
's\\u'
>>> print(s, len(s))   # length of s is 3, not 4
s\u 3

HTH!

dnswlt
  • 2,925
  • 19
  • 15