- [Instructor] To finish up our introduction to
json processing, let's take a look at how you
can print out formatted JavaScript
object notation data so that it's easier to read.
So, if you look back up here, in snippet four,
where we simply listed out the contents of the json file,
it just came out as one long line of information.
But, it would be nice to be able to
read this in a more structured representation.
So, it turns out there is a function in the json module,
called dumps, which stands for dump string.
We're going to use that here to produce a formatted output.
I'll execute it first just so you can see.
And now let's talk about what produced this output.
So, first of all, we opened up the json file that
we wrote to previously for reading and
we're going to call that accounts.
In our print statement here, we have a nested function call.
First, we go to that file called
accounts and we load it up in to memory.
That actually is turning back into the Python object.
Now, we're taking that Python object and
dumping that string of information here in the
context of the Python interactive environment.
Now, the dumps function takes as its first argument an
object that we want to see the string representation of
in json format and the second argument is the indent that
you'd like to use for nesting the contents of the
JavaScript object notation object that's being output.
So, we're using four space indent.
Now, if we look at the original output here in snippet four,
the outer set of curly braces is at the very left edge.
Within that outer set of curly braces, we had the
accounts key and associated with that was a list of values.
So let's look at that.
So here's the accounts key and here's the
beginning of the list and here's the end of the list,
aligned underneath the accounts key and all of the
list items are indented within it.
And as you recall, there were two
dictionary objects inside of there which were
turned into Python, I'm sorry, json objects.
These are those two json objects with their key value pairs,
nicely structured so that you can see them indented
underneath, inside of rather, the list in this case.
So, this first set of curly braces represents the
first json object then we have a comma and
then the second json object in that list of information.
So, by using the dumps function, you can get a nice,
structured, readable string representation
of the JavaScript object notation.
Obviously this is not as compact as
what we saw back here in snippet four but it
does make it a hell of a lot more readable.
And when you're first working with
JavaScript object notation, this dumps function can come in
particularly handy for helping you understand the
structure of the JavaScript object notation that you're
either creating or if you're receiving it from a web service
perhaps, that you're receiving into your application.