2
votes

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.

1
If json.loads won't load it, it isn't valid JSON. - Jared Smith

1 Answers

0
votes

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\\""}'