Python Programmer – Write and check JSON file with Python




import json
import pprint

#generate the JSON file
#will have 2 fields, one is an array (multiple records inside)

#*** make sure the fields and data are written in double quotes

my_json={}
my_json["description"]="This is a json file creation example written in Python"
my_json["data"]=[]
my_data_fields=['id','name']
for i in range(10):	
	my_json["data"].append({"id":i,"name":"name "+str(i)})

#take a look at the JSON output
print my_json

#write the file to the disk
fn='otp.json'
f=open(fn,"w")
f.write(json.dumps(my_json))
f.close()

#Now check if the JSON is valid (can be read as JSON)
json_data=open(fn)

data = json.load(json_data)
pprint.pprint(data)
json_data.close()