0

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"
  }
]
R_Developer
  • 49
  • 1
  • 2
  • 5

2 Answers2

2

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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"}]
user2357112
  • 260,549
  • 28
  • 431
  • 505
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40