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"}
相关推荐
luckys.one1 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
大翻哥哥2 小时前
Python 2025:量化金融与智能交易的新纪元
开发语言·python·金融
zhousenshan3 小时前
Python爬虫常用框架
开发语言·爬虫·python
IMER SIMPLE4 小时前
人工智能-python-深度学习-经典神经网络AlexNet
人工智能·python·深度学习
CodeCraft Studio4 小时前
国产化Word处理组件Spire.DOC教程:使用 Python 将 Markdown 转换为 HTML 的详细教程
python·html·word·markdown·国产化·spire.doc·文档格式转换
小菜全4 小时前
基于若依框架Vue+TS导出PDF文件的方法
javascript·vue.js·前端框架·json
专注API从业者5 小时前
Python/Java 代码示例:手把手教程调用 1688 API 获取商品详情实时数据
java·linux·数据库·python
java1234_小锋5 小时前
[免费]基于Python的协同过滤电影推荐系统(Django+Vue+sqlite+爬虫)【论文+源码+SQL脚本】
python·django·电影推荐系统·协同过滤
看海天一色听风起雨落5 小时前
Python学习之装饰器
开发语言·python·学习
XiaoMu_0016 小时前
基于Python+Streamlit的旅游数据分析与预测系统:从数据可视化到机器学习预测的完整实现
python·信息可视化·旅游