You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

打印字典未出预期结果,REST API请求报400错误如何解决?

解决REST API请求中headers里orderby字段多余转义的问题

问题根源

你手动拼接JSON格式字符串时,因字符串嵌套引号的处理失误,导致生成的orderby字段包含多余的单引号转义,不符合API要求的标准JSON格式,最终引发400 Bad Request错误。

两种可行解决方案

方案1:使用f-string格式化(Python 3.6+)

直接用f-string构造目标字符串,通过双大括号{{}}转义JSON所需的大括号,避免手动拼接的引号混乱:

column = "name"
order = "descending"
headers = {
    'accept': 'application/json',
    'orderby': f'{{"{column}":"{order[:4]}"}}'
}
print(headers)

执行后输出:

{'accept': 'application/json', 'orderby': '{"name":"desc"}'}

方案2:用json模块生成JSON字符串(推荐)

这是最规范健壮的方式,先构造Python字典,再通过json.dumps()转为标准JSON字符串,自动处理所有格式细节,还能兼容字段值含特殊字符的场景:

import json

column = "name"
order = "descending"
# 先构造对应结构的字典
orderby_data = {column: order[:4]}
headers = {
    'accept': 'application/json',
    'orderby': json.dumps(orderby_data)
}
print(headers)

执行后输出完全符合预期,且后续需求变更时更易维护。

内容的提问来源于stack exchange,提问作者Priya Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 22:23:14