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"}
相关推荐
dgfhf几秒前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
Jackey_Song_Odd10 分钟前
Part 1:Python语言核心 - Control Flow 控制流
开发语言·windows·python
阿_旭11 分钟前
【旋转框】基于YOLO26深度学习的无人机视角车辆检测系统【python源码+Pyqt5界面+数据集+训练代码】
python·深度学习·无人机·车辆检测
Pyeako17 分钟前
opencv计算机视觉--PaddleOCR的实时多语言文本检测与识别
人工智能·python·opencv·计算机视觉·ocr·paddleocr
薛定猫AI18 分钟前
【技术干货】基于 NVIDIA API Catalog 与 Kilo CLI 搭建多模型 AI Coding 工作流(附 Python 实战代码)
大数据·人工智能·python
亚马逊云开发者22 分钟前
Bedrock Guardrails 实战:给 AI Agent 装上安全护栏
人工智能·python·安全
cramer_50h22 分钟前
Python的web开发框架Django再次更新
前端·python·django
qq_4176950529 分钟前
用Python创建一个Discord聊天机器人
jvm·数据库·python
2401_8747325329 分钟前
使用Scrapy框架构建分布式爬虫
jvm·数据库·python
淮南颂恩少儿编程30 分钟前
淮南少儿编程 | CSP-J真题详解:在淮南也有接地气的算法课
c++·人工智能·python·深度学习·算法·青少年编程·蓝桥杯