做视频网站需要什么,哪家公司做网站专业,专业做全景图的网站平台,中山建网站费用多少python json字符串怎么用format方法填充参数值报KeyError 需求问题分析解决方案 需求
因为python中的字典和json中的一些变量有差异#xff0c;比如#xff1a;json中有null、true#xff0c;在python中就不会被识别#xff0c;只能转换成字符串#xff0c;在通过loads()… python json字符串怎么用format方法填充参数值报KeyError 需求问题分析解决方案 需求
因为python中的字典和json中的一些变量有差异比如json中有null、true在python中就不会被识别只能转换成字符串在通过loads()的方式转成python的字典。
在把json定义成字符串后需要动态的传递一些参数如下面这个例子
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 Aliceage 30city 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)运行时报错
Traceback (most recent call last):File D:\test\edrms_api_autotest\api\arch_category_api.py, line 37, in modulejson_str json_template.format(name, age, city)
KeyError: nameProcess finished with exit code 1
问题分析
出现 KeyError 异常的原因是在 JSON 字符串中使用了花括号 {} 进行字符串格式化而 JSON 格式中的键名也使用了花括号。因此字符串格式化时无法正确识别字符串中的占位符导致 KeyError 异常的发生。
解决方案
要解决这个问题我们可以使用两个花括号来转义 JSON 字符串中的花括号使其被正确识别为普通字符而非占位符。
修改示例代码如下
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 Aliceage 30city 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)运行结果
{name: Alice, age: 30, city: New York}
{name: Alice, age: 30, city: New York}