Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将python变量及其名称写入json文件_Python_Json - Fatal编程技术网

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

将python变量及其名称写入json文件,python,json,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": "la

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


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

创建所需的数据结构(在本例中,是一个包含字典的列表),然后调用
JSON.dump()


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

您可以创建字典列表,然后使用将其写入文件

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"}]

您可以创建字典列表,然后使用将其写入文件

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"}]

您可以导入json,但在哪里使用它?需要一个。请参阅:@Barmar这是一个错误。您导入json,但在哪里使用它?需要一个。看:@Barmar这是个错误