...

/

Loading Data from a JSON File

Loading Data from a JSON File

We'll cover the following...

Like the pickle module, the json module has a load() function which takes a stream object, reads JSON-encoded data from it, and creates a new Python object that mirrors the JSON data structure.

Press + to interact
shell = 2
print (shell)
#2
del entry #①
print (entry)
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#NameError: name 'entry' is not defined
Press + to interact
import json
with open('entry.json', 'r', encoding='utf-8') as f:
entry = json.load(f) #②
print (entry) #③
#{'comments_link': None,
# 'internal_id': {'__class__': 'bytes', '__value__': [222, 213, 180, 248]},
# 'title': 'Dive into history, 2009 edition',
# 'tags': ['diveintopython', 'docbook', 'html'],
# 'article_link': 'http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition',
# 'published_date': {'__class__': 'time.asctime', '__value__': 'Fri Mar 27 22:20:42 2009'},
# 'published': True}

① For demonstration purposes, switch to Python Shell #2 and delete the entry data structure that you created earlier in this chapter with the pickle module.

② In the simplest case, the json.load() function works the same as the pickle.load() function. You pass in a stream object and it returns a new Python object.

③ I have good news and bad news. Good news first: the json.load() function successfully read the entry.json file you created in Python Shell #1 and created a new Python ...