- [Instructor] In this Self Check exercise,
I'd like you to write out
the grades dict that you see here,
which is a dictionary object in Python.
We'd like you to store that as
Java Script Object Notation in the file grades.JSON.
Then we'd like you to read that file's contents back in
and display the resulting object in pretty printed
JSON format and remember, you can do that with the
dumps function that was part of the JSON module.
So go ahead and pause the video to give that a shot,
and then come back to see the answer.
Okay, let's go ahead and import the JSON module,
and define the dictionary.
And I'll scroll down for the
answer to the other two parts.
So this next snippet is going
to create the file grades.JSON by opening it for writing.
We'll treat that object as the name grades
or assign it to the variable grades
and we will then use
the JSON dump function to take
that grades dict object we defined up above
and write it into the file
that the grades file object refers to.
So let's go ahead and execute that.
At this point, we've created the JSON file
and actually you can see it down here
in the Jupiter Lab listing over on the left side here.
In fact, you know what, let's go ahead
and open that, and notice that it's capable
of giving you this nice, interactive presentation
of what that JSON object looks like in the file.
So that's kind of a cool little feature of Jupiter,
in this case.
But now that we have the file, we can read
the contents back in
and we're going to do that by opening the file for reading.
Again, we'll call the file object grades.
We'll load the contents of that file which will
create an object out of that Java Script Object Notation.
We're then going to take that object and pass it to dumps
and display the formatted Java Script Object Notation with
indents of four.
So if I go ahead and execute that,
you can see the Java Script Object Notation down here.
Again, it uses double quotes rather than single quotes
for strings in the context of Java Script Object Notation.
The outer set of curly braces represents the entire object.
Our entire object had one key-value pair, which was the
grade book and its list of students.
Each of the three students
that we had in the grade book is represented
as a set of curly braces
which means another Java Script Object Notation object,
and within each of those objects
we have key value pairs representing each student's
id, name, and grade.