Quick Example and Walk-Through JSON with Python
This is a quick to create a dictionary object , write it to a JSON file and then read back the file and convert it to a dictionary and access the items in the dictionary.
Credit to : codebasics. You can check him out on Youtube
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# lets create a dictionary of books book = {} book['Tom'] = { 'name':'Tom', 'address':'1 red street, NY', 'phone':98988988 } book['Bob'] = { 'name':'Bob', 'address':'1 green street, NY', 'phone':252525885 } |
1 2 3 4 |
#import json and pass the dictionary to it import json s = json.dumps(book) s |
1 2 3 |
#lets write the string returned by json to a txt file with open('C://Users//adaba//Documents//Coursera//Projects//writeToTxt.txt', 'w') as f: f.write(s) |
1 2 3 4 |
#lets read back the file f = open('C://Users//adaba//Documents//Coursera//Projects//writeToTxt.txt', 'r') read_s = f.read() read_s |
1 2 |
#lets check the type of data of the returned item type(read_s) |
1 2 |
# it is a json string object. we want to get it back into a dictionary format so we can work with it easily book_read_back = json.loads(read_s) |
1 2 |
#lets see the result returned by json book_read_back |
1 2 |
#what data type is it? type(book_read_back) |
1 2 |
#lets check the records/details for Bob book_read_back['Bob'] |
1 2 |
#lets check Bob's phone number book_read_back['Bob']['phone'] |
1 2 3 |
#lets get all the records from dictionary for person in book_read_back: print(book_read_back[person]) |