Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python program to write to json from input

I made a program in python3 that writes to json upon input from user. Program is running but includes slashes

i want it to be

Output:(written to a file sample.json)

 {
     "api" : api_key=4ewrs5798hoknlkmnnmhbvjgfd7" 
 }  

But instead i get

Output:(written to a file sample.json)

{\"api\":\"api_key=4ewrs5798hoknlkmnnmhbvjgfd7\"}"

Backslash appears at every (") also indents are missing even if declared or not

import json
k1 = input("enter key")
k2 ='{"api" : ""api_key='+k1+'"}'

with open("sample.json", "w") as outfile: 
    json.dump(k2, outfile, indent=4)
print("success")
like image 259
Sandeep Avatar asked Oct 21 '25 17:10

Sandeep


1 Answers

The problem has to do with the quotations you are using in k2. A better way of doing this is to use dicts.

import json
k2 = {}
k2['api'] = "api_key=" + input("enter key")

with open("sample.json", "w") as outfile:
    json.dump(k2, outfile, indent=4)
print("success")
like image 51
Sri Avatar answered Oct 23 '25 07:10

Sri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!