Reading From JSON
It’s pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It’s done by using the json module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.
Deserialization of JSON
The Deserialization of JSON means the conversion of JSON objects into their respective Python objects. The load()/loads() method is used for it. If you have used JSON data from another program or obtained as a string format of JSON, then it can easily be deserialized with load()/loads(), which is usually used to load from string, otherwise the root object is in list or dict. See the following table given below.
|JSON OBJECT||PYTHON OBJECT|
- json.load(): json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.
- Example: Suppose the JSON file looks like this:
- We want to read the content of this file. Below is the implementation.
- json.loads(): If you have a JSON string, you can parse it by using the json.loads() method.json.loads() does not take the file path, but the file contents as a string, using fileobject.read() with json.loads() we can return the content of the file.
json.loads(jsonstring) #for Json string json.loads(fileobject.read()) #for fileobject
- Example: This example shows reading from both string and JSON file. The file shown above is used.