gpt4 book ai didi

python - 如何解析 JSON 字符串中转义的双引号

转载 作者:太空宇宙 更新时间:2023-11-03 21:33:03 25 4
gpt4 key购买 nike

从 API 中,我得到了以下 JSON 字符串,我想将其转换为 python 字典。

{
"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: Expecting property name: line 3 column 97 (char 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\" 处的转义存在问题。

如何将 API 中的 json 字符串分配给 python 字符串对象,并使用 json.loads(s) 将其转换为 dict ?

json.loads(json.dumps(s)) 不起作用。

最佳答案

在控制台中进行快速测试似乎证明双引号应该是双重转义的(\\)。您正在寻找的答案是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 question 中的答案有些相同。和 this question

<小时/>

使用替换:

>>> tmpstr = '{"title" : "foo", "desc": "foo\"bar\""}'
>>> tempStr.replace('"', '\"')
'{"title" : "foo", "desc": "foo\\"bar\\""}'

关于python - 如何解析 JSON 字符串中转义的双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53420114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com