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"}
相关推荐
消失的旧时光-19436 分钟前
第六篇:Redis Hash——一个用户对象应该保存成 JSON,还是保存成 Hash?
redis·json·哈希算法
MC皮蛋侠客17 分钟前
SQLAlchemy 系列(十一):从 1.x 到 2.x——渐进迁移与数据访问层治理
数据库·python
魔镜前的帅比30 分钟前
(开源项目)x-claw (设计)
python·ai·rust·开源
谢尔登1 小时前
分享一些我常用的Skill
java·人工智能·python·actionscript
k4m7v2pz2 小时前
macOS 解压 40GB 分卷+中文密码固件镜像的五个深坑与解决方案
python·7-zip·aes加密·踩坑记录·r36s·多卷zip解压
小白学大数据2 小时前
Python 爬虫实战:抓取汽车之家二手车成交价格与里程数据
开发语言·爬虫·python·汽车
Jazz_z2 小时前
如何用Python将彩色PDF一键转为黑白(灰度)
java·python·pdf
SEO_juper3 小时前
2026年Schema自动注入实战:用Python批量给1000个页面加上JSON-LD,AI引用率实测提升38%
人工智能·python·json·seo·独立站
zzzll11113 小时前
HashMap、HashTable、ConcurrentHashMap 详细区别与深度解析
开发语言·python
程序员AI工坊3 小时前
Agent 开发:ReAct 循环与工具调用实战——从单次调用到自主 Agent
人工智能·后端·python·langchain·agent·react