Skip to content Skip to sidebar Skip to footer

Json.loads(jsonstring) In Python Fails If String Has A "\r" I.e. Carriage Return Character

I am getting a JSON string which has a '\r' character somewhere e.g. '{'data':'foo \r\n bar'}' when I try to parse it throws ValueError. >>> j='''{'data':'foo \r\n bar'}''

Solution 1:

You should escape slashes in JSON:

j="""{"data":"foo \\r\\n bar"}"""

If you are not escaping them, your JSON is invalid (being valid Python string).

Solution 2:

Logically python is doing what should have been done !

Its the same old CRLF (inspired from typewriters) CR = Carraige Return LF = Line Feed

'\r' stands for CR But '\n' = CR + LF so, my point is that for json its definitely not valid.

For Eg: print '\n 123456\rone' # one3456

Now, how to use \r anyway ?

# if j is your jsonj = j.replace('\r','\\r')

That should only escape \r with \\r

Post a Comment for "Json.loads(jsonstring) In Python Fails If String Has A "\r" I.e. Carriage Return Character"