简体   繁体   中英

Write python variables with their names to json file

I'm writing python variables to json file and I want to include their name with them.

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

import json
with open("file.json", "w") as f:
    f.write(f_name+' '+ l_name)

output in json file :

first name last name

I want the output to be like this

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

Create the data structure that you want (in your case, a list containing a dictionary), and call json.dump() .

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

Don't use wb mode when creating a JSON file. JSON is text, not binary.

You can create the list of dictionaries, and then use https://docs.python.org/3/library/json.html#json.dump to write it into the file

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)

The content of the json file would look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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