1

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.