首页 > 解决方案 > 如何替换 JSON 字典值中的引号?

问题描述

我正在使用Open Trivia DB的 API 来生成琐事问题。

import requests, json, urllib.parse
import 

url = "https://opentdb.com/api.php"

querystring = {"amount":"5","type":"multiple","encode":"url3986"}

response = requests.request("GET", url, params=querystring)
response_decoded = urllib.parse.unquote(response.text)
print(response_decoded)
response_dict = json.loads(response_decoded)
print(response_dict["results"][0])

但是,我不断遇到一些错误,错误是:

Exception has occurred: JSONDecodeError
Expecting ',' delimiter: line 1 column 347 (char 346)

我发现错误是因为在某些类似于 的问题中Who is the main character in "gamename",游戏名称周围有引号。在我返回的 JSON 的上下文中,它看起来像这样:

"question":"Who is the main character in "gamename"?",
"correct_answer":"maincharacter",
"incorrect_answers":["wrongname1","wrongname2","wrongname3"]

并且游戏名周围的引号弄乱了字典。

有没有办法让我只将内部引号(围绕游戏名)替换为单引号',,这样它就不会弄乱字典结构?

标签: pythonjsondictionary

解决方案


通过解码原始字符串,您会导致 JSON 格式错误。相反,你可以json.loads先。当您需要输出它的任何部分时,您可以使用urllib.

另一种更脆弱的方法是做类似的事情

response_decoded = urllib.parse.unquote(response.text.replace('"', '~')).replace('"', r'\"').replace('~', '"').

~您可以使用与遇到任何问题时不同的角色;我只是选择了一些不寻常的东西。


推荐阅读