python - 将带有名称的python变量写入json文件
问题描述
我正在将 python 变量写入 json 文件,我想在其中包含它们的名称。
f_name= 'first name'
l_name= 'last name'
import json
with open("file.json", "w") as f:
f.write(f_name+' '+ l_name)
json文件中的输出:
first name last name
我希望输出是这样的
[
{
"f_name": "first name",
"l_name": "last name"
}
]
解决方案
创建您想要的数据结构(在您的情况下,是一个包含字典的列表),然后调用json.dump()
.
with open("file.json", "w") as f:
json.dump([{"f_name": f_name, "l_name": l_name}], f)
wb
创建 JSON 文件时不要使用模式。JSON 是文本,而不是二进制。
推荐阅读
- java - 为什么 restful 服务需要框架
- java - 删除 EFS 中的文件时出现过时文件句柄错误
- html - 是否可以更改 Shiny Dashboard 标题中单个字符的颜色?
- c# - SimpleStub 中的 MockBehavior.Loose 和 MockBehavior.Strict 有什么区别?
- leaflet - 设置dashArray时如何使用两种颜色设置Leaflet折线?
- javascript - 桌面 Chrome 中的图像加载
- javascript - 无需使用 Google Analytics 进行身份验证即可显示访问者数量
- android - 如何在cardview中插入背景图片?
- c++ - OpenCL 将 float16 转换为 float*
- python - 未找到与 socketserver 匹配的发行版