简体   繁体   中英

How to handle brace escape in json

I have a json format string to be loaded with python2, but it will be error when json.loads() .

{"api":"wdetail","v":"5.0","ret":["100"],"data":{"apiStack":[{"name":"esi","value":"{\\"api\\":\\"com.aaa.detail\\",\\"v\\":\\"1.0\\",\\"ret\\":[\\"11\\"]}"}]}}

when loads above json string, it will prompt error: ValueError: Expecting , delimiter: line 1 column 87 (char 86) , I found that is because there quote mark before brace in "value":"{\\"api\\" , if I remove quote mark, json loads works.

{"api":"wdetail","v":"5.0","ret":["100"],"data":{"apiStack":[{"name":"esi","value":{\\"api\\":\\"com.aaa.detail\\",\\"v\\":\\"1.0\\",\\"ret\\":[\\"11\\"]}}]}}

About first string, how can I ask json.loads to support it. otherwise, I need to remove quote mark one by one which is bored.

You can use str.replace() to remove "{ and }" from your first string:

new_s = s.replace('"{', '{').replace('}"', '}')  # s is your first string here
data = json.loads(new_s)

Since we are talking about json.loads() means that you are reading files. you can do so with bash and the amazing sed

sed -i 's/"{/{/g' filename.json && sed -i 's/}"/}/g' filename.json

and if you wanna be very cool you can even use a fabric script!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM