课程: Python Essential Training

JSON

- [Instructor] Previously, we've been focusing a lot on reading and writing files to and from the disk. JSON files with the .json extension are common, of course, and you might regularly be working with them. But for now, we'll mostly be focusing with JSON strings. I'm going to assume by this point that you're pretty good at reading files from the disk. You can load their contents into a string and now you find yourself with a JSON string. So what do you do? Well, let's make a JSON string, a is apple, b is bear, c is cat. Okay. Something to keep in mind, JSON is not Python. This JSON formatted string looks a lot like a Python dictionary, but it's not. It's a string. I've seen a lot of even very experienced programmers get confused about this and lose track of what they're working with. This is a string that just happens to be in the JSON format. And in order to turn it into a dictionary, we need to import the JSON module at the top of our notebook, import json, and then we're going to use a method called json.loads and pass in the string, jsonString. Notice that this is called loads plural and not load singular. Another common mistake. So now we have a Python dictionary. I can copy this Python dictionary and add a trailing comma, and that's just fine. But if I add a trailing comma to this JSON string, we get a JSON decode error. So it's very common if you're working with JSON from a potentially untrustworthy source to surround this json.loads with a try except JSONDecodeError:print Could not parse JSON. And because this JSONDecodeError comes from the JSON module, we need to specifically import it as well. So from json import JSONDecodeError. So that's reading JSON, but what about going in the opposite direction, dumping a Python dictionary into a JSON string? For this, use the json.dumps method. So here's my pythonDict, I'm going to use json.dumps pythonDict. And again, notice that this is dumps plural. You usually wouldn't add any exception handling in this case because if you have a valid Python dictionary, there's not a lot that could go wrong when you're formatting it as a JSON string. However, there is one exception to this rule where an exception could be thrown. And to demonstrate that, let's create an animal class real quick, class Animal init self, name, self.name equals name, and let's modify our dictionary to use this Animal class. Obviously an apple isn't an animal, so I'm going to replace this with aardvark and just put that in there. Animal bear and Animal cat. Okay, now let's dump this dictionary. Whoops. Animal. There we go. Okay, so you see that we get a TypeError, Object of type Animal is not JSON serializable. The JSON module has no idea how to handle this Animal class. It doesn't know what the JSON equivalent should be. What we do here is override the default JSON encoder that it's using with a JSON encoder of our own. So first, we're going to import the JSONEncoder. All right, and now we can make one. So we're going to extend the JSONEncoder class to create a new AnimalEncoder class JSONEncoder. All right, and the only thing we need to override here is the default method, so def default self and o. O is the object that's being passed in here that needs to be decoded into JSON. So if type o is equal to Animal, if we're dealing with an Animal object, return o.name. Else, return super default o. So if it's not an animal, we pass it off to the parent version of the encoder by using super, which is the parent JSONEncoder class and then calling that default method. And then we need to let JSON dumps know that it needs to use this encoder and we can do that by passing the cls keyword argument, AnimalEncoder, and there you go. Again, generally, you don't need to surround json.dumps in a try except statement because you're usually creating the dictionaries that you pass into json.dumps in your own code, and you should appropriately handle any data types that you're passing in there. But if you get any crazy JSON formatted files from unknown sources, it's best to beware. Stay safe out there.

内容