Reading and Writing JSON through Python -


read.json file :

{     "username" : "admin",     "password" : "admin",     "iterations" : 5,     "decimal" : 5.5,     "tags" : ["hello", "bye"],     "value" : 5 } 

program.py file:

import json  open('read.json') data_file:     data = json.load(data_file)  data = str(data) data.replace("'",'""',10) f = open("write.json", "w") f.write(data) 

write.json file :

{'username': 'admin', 'password': 'admin', 'iterations': 5, 'decimal': 5.5, 'tags': ["hello", "bye"], 'value': 5} 

what want achieve :

  1. read json data read.json file
  2. parse , modify values json in program
  3. write write.json file (in json format)

there no errors in code, write.json not contain values in double quotes(""), rather values wrapped in single quotes making not proper json format.

what change needs done make write.json file contain proper json format , 'pretty-write' write.json file.

you can directly dump json data file. docs

import json open('read.json', 'w') outfile:     json.dump(data, outfile, sort_keys=true, indent=4)     # sort_keys, indent optional , used pretty-write  

to read json file:

with open('read.json') data_file:         data = json.load(data_file) 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -