python json字符串怎么用format方法填充参数值报KeyError

python json字符串怎么用format方法填充参数值报KeyError

需求

因为python中的字典和json中的一些变量有差异,比如:json中有null、true,在python中就不会被识别,只能转换成字符串,在通过loads()的方式转成python的字典。

在把json定义成字符串后,需要动态的传递一些参数,如下面这个例子:

bash 复制代码
if __name__ == '__main__':
    # tkn = util_tools.get_api_tkn()
    # template_api = ArchCategoryApi(tkn)
    # res = template_api.get_template_list()
    # print(res)

    json_template = '{"name": "{}", "age": "{}", "city": "{}"}'

    # 参数列表
    name = "Alice"
    age = 30
    city = "New York"

    # 使用 format 方法填充参数
    json_str = json_template.format(name, age, city)

    # 将字符串转换为字典
    json_dict = json.loads(json_str)

    # 验证字典内容
    print(json_dict)

    # 将字典转换回 JSON 字符串
    json_str_final = json.dumps(json_dict)
    print(json_str_final)

运行时报错:

bash 复制代码
Traceback (most recent call last):
  File "D:\test\edrms_api_autotest\api\arch_category_api.py", line 37, in <module>
    json_str = json_template.format(name, age, city)
KeyError: '"name"'

Process finished with exit code 1

问题分析

出现 KeyError 异常的原因是在 JSON 字符串中使用了花括号 {} 进行字符串格式化,而 JSON 格式中的键名也使用了花括号。因此,字符串格式化时无法正确识别字符串中的占位符,导致 KeyError 异常的发生。

解决方案

要解决这个问题,我们可以使用两个花括号来转义 JSON 字符串中的花括号,使其被正确识别为普通字符而非占位符。

修改示例代码如下:

bash 复制代码
if __name__ == '__main__':
    # tkn = util_tools.get_api_tkn()
    # template_api = ArchCategoryApi(tkn)
    # res = template_api.get_template_list()
    # print(res)

    json_template = '{{"name": "{}", "age": "{}", "city": "{}"}}'

    # 参数列表
    name = "Alice"
    age = 30
    city = "New York"

    # 使用 format 方法填充参数
    json_str = json_template.format(name, age, city)

    # 将字符串转换为字典
    json_dict = json.loads(json_str)

    # 验证字典内容
    print(json_dict)

    # 将字典转换回 JSON 字符串
    json_str_final = json.dumps(json_dict)
    print(json_str_final)

运行结果:

bash 复制代码
{'name': 'Alice', 'age': '30', 'city': 'New York'}
{"name": "Alice", "age": "30", "city": "New York"}
相关推荐
prince_zxill31 分钟前
把 17 个散文件装进一个文件夹:拆解 claude-plugins-official 的插件打包术(47,413 Star 实测)
python·github·agent·mcp·claude code
少司府43 分钟前
嵌入式外设篇(三)GPIO·三:MCU系统结构、总线与统一编制
linux·python·stm32·单片机·嵌入式硬件·mcu·嵌入式软件
伞伞悦读1 小时前
【第90期】KNN分类回归流水线与K值对照的实验与排查
大数据·人工智能·python·深度学习·机器学习
console.log('npc')2 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
honker_X2 小时前
Python字符串全攻略:从入门到精通
开发语言·python
贾公子3 小时前
异步检测的轮询与超时——别把「还没好」当成「失败了」
后端·python
吃我一窝jio3 小时前
Docker+Jenkins+K8s全流程部署
java·开发语言·笔记·python
欢乐马87914 小时前
优化|MPSolver 和 pywraplp 到底谁是谁?一次讲清 OR-Tools 的三层结构
python
mengge.cloud5 小时前
Python基础保姆级!从入门到入土
开发语言·python·云原生·pygame
qq_1588954111110 小时前
Suno-API 是什么?官方 V6 模型与 Python / TypeScript 接入指南
python·ai音乐·suno api