[英]Ansible and jinja - Sending double-quote escaped JSON string into AWS
[英]How to parse escaped Double Quote in JSON String
從API中,我得到了要轉換為python dict的JSON字符串。
{
"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"
}
如果我嘗試使用json.loads()
加載它,則會給我一個錯誤
ValueError:預期的屬性名稱:第3行第97列(字符136)
但是,如果我嘗試將此字符串用作原始字符串,則它可以工作。
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"
}"""
我認為逃脫(height 5'8\\", chest 33\\"
。
如何將這個json字符串從API分配給python字符串對象,然后使用json.loads(s)
將其轉換為dict?
json.loads(json.dumps(s))不起作用。
在控制台中對此進行的快速測試似乎證明應該對雙引號( \\\\
)進行兩次轉義。 您正在尋找的答案是Python:如何在json字符串值內轉義雙引號?
>>> tempStr = '{"title" : "foo", "desc": "foo\\"bar\\""}'
>>> temp2 = json.loads(tempStr)
>>> temp2
{'title': 'foo', 'desc': 'foo"bar"'}
使用替換:
>>> tmpstr = '{"title" : "foo", "desc": "foo\"bar\""}'
>>> tempStr.replace('"', '\"')
'{"title" : "foo", "desc": "foo\\"bar\\""}'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.