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"}
相关推荐
databook11 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar12 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户83562907805113 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_13 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机19 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机20 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机20 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机20 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i21 小时前
drf初步梳理
python·django
每日AI新事件21 小时前
python的异步函数
python