2

From an API I am getting following JSON String which I want to convert into python dict.

{
    "title":"size_fit_desc",
    "description":"\u003Cp\u003ERegular Fit\u003Cbr \u002F\u003EThe model (height 5'8\", chest 33\" and waist 28\") is wearing a size M.\u003C\u002Fp\u003E"
}

If I try to load it using json.loads() It gives me an error

ValueError: Expecting property name: line 3 column 97 (char 136)

However If I try to use this string as raw string then it works.

s = r"""{
        "title":"size_fit_desc",
        description":"\u003Cp\u003ERegular Fit\u003Cbr \u002F\u003EThe model (height 5'8\", chest 33\" and waist 28\") is wearing a size M.\u003C\u002Fp\u003E"
}"""

I think there an issue with an escaping at (height 5'8\", chest 33\".

How can I assign this json string from API to python string object and convert it into dict using json.loads(s) ?

json.loads(json.dumps(s)) does not work.

Jake R
  • 21
  • 4
  • Possible duplicate of [Python: How to escape double quote inside json string value?](https://stackoverflow.com/questions/40150405/python-how-to-escape-double-quote-inside-json-string-value) – LoneWanderer Nov 21 '18 at 20:55
  • If `json.loads` won't load it, it isn't valid JSON. – Jared Smith Nov 21 '18 at 21:27

1 Answers1

0

A quick test in console with this seems to proove that the doube-quotes should be double-escaped (\\). The answer you are looking for is Python: How to escape double quote inside json string value?

>>> tempStr = '{"title" : "foo", "desc": "foo\\"bar\\""}'
>>> temp2 = json.loads(tempStr)
>>> temp2
{'title': 'foo', 'desc': 'foo"bar"'}

This is sometwhat the same answer as in this question and this question


Using replacement:

>>> tmpstr = '{"title" : "foo", "desc": "foo\"bar\""}'
>>> tempStr.replace('"', '\"')
'{"title" : "foo", "desc": "foo\\"bar\\""}'
LoneWanderer
  • 3,058
  • 1
  • 23
  • 41
  • I am still confused. How did you convert '{"title" : "foo", "desc": "foo\"bar\""}' into '{"title" : "foo", "desc": "foo\\"bar\\""}' – Jake R Nov 21 '18 at 21:04
  • I did it by hand for the sake of explanation. The refrenced SO answer explains what you can do to perform the conversion programmatically. – LoneWanderer Nov 21 '18 at 21:07
  • I tried but it does not give desired output. `>>> tempStr = '{"title" : "foo", "desc": "foo\\"bar\\""}'` `>>> tempStr = '{"title" : "foo", "desc": "foo\"bar\""}'` `>>> print tempStr.replace('"', '\\"')` `{\"title\" : \"foo\", \"desc\": \"foo\"bar\"\"}` >>> ` – Jake R Nov 21 '18 at 21:12
  • You need to focus on what the `replace` is supposed to do. – LoneWanderer Nov 21 '18 at 21:19