首页 > 解决方案 > 将带有名称的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"
  }
]

标签: pythonjson

解决方案


创建您想要的数据结构(在您的情况下,是一个包含字典的列表),然后调用json.dump().

with open("file.json", "w") as f:
    json.dump([{"f_name": f_name, "l_name": l_name}], f)

wb创建 JSON 文件时不要使用模式。JSON 是文本,而不是二进制。


推荐阅读