繁体   English   中英

将python变量及其名称写入json文件

[英]Write python variables with their names to json file

我正在将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)

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

您可以创建词典列表,然后使用https://docs.python.org/3/library/json.html#json.dump将其写入文件

import json

f_name= 'first name'
l_name= 'last name'

#Create the list of dictionary
result = [{'f_name': f_name, 'l_name': l_name}]

import json
with open("file.json", "w") as f:
    #Write it to file
    json.dump(result, f)

json文件的内容看起来像

[{"f_name": "first name", "l_name": "last name"}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM