python - 如何替换 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"]
并且游戏名周围的引号弄乱了字典。
有没有办法让我只将内部引号(围绕游戏名)替换为单引号'
,,这样它就不会弄乱字典结构?
解决方案
通过解码原始字符串,您会导致 JSON 格式错误。相反,你可以json.loads
先。当您需要输出它的任何部分时,您可以使用urllib
.
另一种更脆弱的方法是做类似的事情
response_decoded = urllib.parse.unquote(response.text.replace('"', '~')).replace('"', r'\"').replace('~', '"').
~
您可以使用与遇到任何问题时不同的角色;我只是选择了一些不寻常的东西。
推荐阅读
- docker - Nginx CORS 政策问题
- ruby-on-rails - Rails 嵌套 jsonb 查询
- netflix-eureka - 随机客户端发现尤里卡
- jmeter - 如何在Jmeter中找到整个线程组的平均响应时间
- sharepoint - 基于相同表单的另一个字段创建下拉列表 - Sharepoint 2013 List
- firebase - 如何拉取 Firebase Bootstrap 网站代码
- python - Python序列集群练习
- sockets - 通过蜂窝数据或互联网的 TCP 套接字连接
- java - 如何在java中做一个循环双向链表添加方法
- go - 提交表单时如何检查输入文件是否为空?