json.dump()
By using file object in Python we can write Json formatted data to a file using dump() method.
« Json
Using List
import json
my_list=['Alex','Ronald','Ronny']
fob=open('data_j3.txt','w')
json.dump(my_list, fob)
fob.close()
Using Dictionary
import json
my_dict={1:'Alex',2:'Ronald',3:'Ronny'}
with open("data_j2.json", "w") as fob:
json.dump(my_dict, fob)
fob.close()
import json
my_dict={1:'Alex',2:'Ronald'}
fob=open('data_j.txt','w')
json.dump(my_dict, fob)
fob.close()
All above scripts will create text files and these files can be checked for Json data format. Here is one sample code to read the data from a file.
fob=open('data_j2.json','r')
print(fob.read()) # {"1": "Alex", "2": "Ronald", "3": "Ronny"}
fob.close()
load() to read Json data from file
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com