JavaScript Object Notation (JSON) | Python for Beginners [38 of 44]

>>Okay. So when we
looked at calling an API, we finished by getting
some data back in this big dump of data and
it was a little confusing, that data we got back was JSON. So what I want to do now is
show you how to navigate that JSON structure because it’s
a little scary at first glance. JSON is a standard data format that’s used to pass
data back and forth, but it can be very
intimidating at first glance. What you see here is
the actual JSON that was returned by my API call when I passed in a picture
of a polar bear, and asked the analyze ImageService to tell me
what was in the image. This is the data that
came back, but it said, it looks a little scary
when you just look at it or displayed that way, how would I read this using code? Well, the first thing
you want to do is, there’s a whole bunch
of websites and things out there called JSON linters, like link you find in a dryer. What that will do for you, is if you take some JSON and
you put it into a linter, it’ll format it nicely so that you as a person have
an easier time reading it. So that’s going to
make your life easier. First thing I do,
when I get a chunk of JSON is put it on to go to
a website, but does linting, copy and paste the JSON there, and then I look at it this way
and I look at ii and I say, “Oh now I see what’s coming back.” What I’m getting back is, so I had a variable called results, which held the code
that was passed back, and I can see it gave me back a color that was in the image and they told me that dominant color in
the foreground and the background, and the accent colors and whether or not it was
a black and white image. For some reason, it gives you
that tag twice not sure why. Then it gave me a description, telling me the tags of what
it saw inside the image. It’s a bear, polar bear,
it’s an animal, a mammal, outdoor, it’s a water, white, large, and so on. It tells me a caption
that it generated. This is a large white polar
bear walking in the water, and requestId, which uniquely
identifies my call to that API. So this is what actually
was passed back when I call the analyze ImageService
and I passed it my image. This is what it found inside the image based on the parameters
and so on I passed in. Now, how do I use this encode? How do I actually
write code that reads through this messy-looking JSON, but even though it
is very structured? Basically what you’ll
notice is there’s a pattern to how the JSON data looks. It’s basically a series of key pairs. So you have a key, requestId, and a value, the value of
the actual requestId itself. Sometimes the pattern is, you have a key and
for that key there is a series of subkeys and subvalues. So for color, you’ll notice
there was for each color, it said Verres be
dominantColorForeground, dominantColorBackground, dominantColors, and for
each those is a value. So this is an example
where I have a series of subkeys and sub values
for the key of color, or for a particular key you
might have a list of values, like we did with the tags. So tags is the key and for the tags, there is multiple values
that are specified. So it saw it was a bear,
it knew it was an animal, it knew the pitcher was outdoors, it saw water, it knew it was white. So all of those are tagged, so you’ll see the square brackets
indicate it’s a list of values. Those are all different tags. So they’re all a list of values
that go with the tags key. So when we want to read
this with our code, we have to know which of
these structures we’re dealing with. So there is different methods we use to basically read
through the JSON, and we have to read it slightly differently depending
on whether it’s a key, value, key and subkeys, or key and oldest of values. Let’s say you want to
retrieve the value from just a straight key value, this is the easiest one to do. What we do is, we’re going
to import the JSON library, and with them what we can do is, with our results, so
I’m assuming when I call the code and I
call the web service, the results were passed back
to a variable called results. So results is name of the variable that contains
that big JSON string. So all I have to do is say, “Give me the value
of that requestId.” Basically, it’ll return to
me that value for the key. So you pass it the key, it will return to you the value. Now, what if I need
to retrieve a value, that’s in one of these keys subkeys? So I have the color key, and for the color key, I want to know the dominantColor
in the background, like what’s the primary color of this image? In this case, “White.” So what I have to do, and you can think of like
a series of file folders, I have to say, “Well,
go into the color key, and in the color key, go down to the
dominantColourBackgrounds.” So think of this as like
folder and sub-folder. Then, say go to color,
dominantColorBackground, that’s the key name I want and it
will return the value of White. So it returns the value
of the key I specified. So I said think of this like
a folder and a subfolder, might be an easy way to
think of how you drill down and specify the key you
want when the’re subkeys. Now, if you have a value in a list, so my JSON when it came
back for description, the tags there was a whole list of possible actual values
returned for the tags. So what if I want
the first value in the list? Well, if you think back to
that module we did on list, we had index positions to indicate first index zero is the
first one in the list, one is the second list, and so on. So what I can do is, I can say use desscription say go
to description tags. So go to the description key, under description key,
go to the tags key, and then just get the index number of a particular tag you want back, zero. Of course, most of the time, and that will return bear, but most of the time
you probably just want all of the tags that came back, so to do that, you
would just use a loop. So I can simply say, “For each item in results
description tags. So if you go to description tags, for each item in this list
printed on the screen.” That allows me to go through
literally and display every single tag that was
returned in the JSON. In addition to needing to read JSON, there is going to be times when
you might need to create JSON to. You might be required to create.JSON
to pass to a web service. So if that’s the case, how do I actually create
JSON with my code? Usually, we use dictionaries. So dictionaries had that same
concept of key value pairs. So since JSON has key value pairs, the python dictionary is like
the perfect mapping to it. So the good news is, you can use the JSON library and you can actually use
the JSON dumps message, give it a dictionary and it’ll
create.JSON from the dictionary. But exactly, how you
create the dictionary depends on which of those three
structures you want to create. If you just want to
create key-value pairs, like I might create a dictionary
object here for a person, we saw this when Christopher covered
dictionaries and collections. I have a firstname of Christopher
and last name of Harrison, and that’s two key value pairs
and putting in the dictionary. Then you can add
additional key pairs if you need to add another key
called Seattle with a value, sorry, key of city in
the value of Seattle. Then I use the JSON library to
say, “Hey, use json.dumps.” This is one of the features
of the library, pass it the dictionary, and that will return a JSON object. Then if I print that
out, you can see, it shows me the three
key-value pairs. So if all you need is key-value, key value, key value, just create a dictionary, use json.dumps to create
that into a JSON object. What if I need that key subkey, okay? If you need those subkeys
and subvalues, it’s little more complicated, but what you’re really
doing is creating a dictionary in a dictionary,
if that makes sense. You’ll have to play with this
to practice and get used to it. So I have that person dictionary, which contains
Christopher’s firstname, Christopher, lastname is Harrison, just like I did before. But imagine if I had a JSON object which showed us our staff directory, and each staff position, there is a person associated with it. For that person, we
know they’re firstname, lastname, what city they
live in, and so on. So I might have a staff dictionary which has a key of Program Manager, and the Program Manager
is a particular person, and for that person
there is firstname, lastname, city, and so on. So what I do in this case, I create the staff dictionary, and then I create the Key Program
Manager from staff dictionary, but instead of just saying
it equals Christopher, I say it equals the dictionary
object, which contains Christopher. Then, you actually get
that nested set of subkeys when you create a JSON object from that dictionary nested
in a dictionary. If you need to create a JSON object that contains
that list of values, then instead of putting
a dictionary in the dictionary, you actually put a list
in your dictionary. So again in that module
on collections, we learned how to create lists. So what I can do is, create my person dictionary. first key is equal to
the value Christopher, the last key is equal to
the value of Harrison. Then, I create a list of all the
programming languages he knows, and I say he knows CSharp,
Python, and JavaScript. So this is just a Python list object. Then I create a new key in my
person dictionary called languages, and set it to the entire list. Then I take that person dictionary, change it into JSON andn now I have
that list embedded in my JSON. So those are the three basic
scenarios you’ll be playing with if you’re trying to create
JSON with your Python code. It takes awhile to get used to this. Chances are, you won’t get the
code right on the first time, the first time you have to
read JSON or write JSON, so a couple of tips to help you out. One, use print statements all
over the place to help you debug. When you do a json.dumps
to create the JSON object, print that JSON object out to make sure it looks
the way you expected. When you’re trying to read JSON, you may want to do print statements
to show the values you read and gradually work it out until
you figure out the rates in text to get the rate subkey
and the rate list item. So play around with print statements, they we’ll really help you
master your JSON skills. Use a JSON linting tool,
just go on the web, search for JSON Linter, then you copy and
paste your JSON to it, and it will give you
that nice formatted view, that’s a lot easier
for humans to read, so you can see the pattern of keys and subkeys or keys and list values, and see which ones go together. Finally, I actually find it useful the first time I call
an API that returns JSON, I actually usually copy and
paste that JSON lint it, and then I keep it in something like a Word document on
the side to refer to as references since I’m
trying to figure out how to navigate the JSON and
read what I need. So that’s the theory, let’s try it
out and practice and some code.


Add a Comment

Your email address will not be published. Required fields are marked *