krishna reddy
krishna reddy

Reputation: 325

How to add a proper escape sequence character into string

I have defined variable 'a' with a value of a dictionary as a string. Got an error when trying to load that string as json.

>>> a = '{"key":"^~\\&"}'
>>> data = json.loads(a, object_pairs_hook=OrderedDict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 352, in loads
    return cls(encoding=encoding, **kw).decode(s)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Invalid \escape: line 1 column 9 (char 8)
>>> 

Is there a way to make this happen

Upvotes: 1

Views: 81

Answers (2)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

using raw strings avoids that python "eats" one backslash, and then loading works:

>>> a = r'{"key":"^~\\&"}'
>>> print(json.loads(a))
{'key': '^~\\&'}

the backslash is still doubled because of the representation of the string but here:

>>> print(json.loads(a)["key"])
^~\&

it works fine

Of course, if your data already contains the string in question, raw strings won't help. In that case use replace:

>>> a = '{"key":"^~\\&"}'  # wrong
>>> a = a.replace("\\","\\\\")
>>> print(json.dumps(json.loads(a)))
{"key": "^~\\&"}

works too.

Upvotes: 1

ruohola
ruohola

Reputation: 24038

When dealing with strings which include backslashes you should always use raw string literals:
(just put r before the string)

>>> a = r'{"key":"^~\\&"}'
>>> data = json.loads(a, object_pairs_hook=OrderedDict)

Upvotes: 0

Related Questions