Home > Article > Backend Development > How to process JSON data using Python
How to use Python to process JSON data? This article will introduce you to the basic methods of using Python to process JSON data. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Before introducing the basic methods of using Python to process JSON data, we must first understandWhat is JSON?
JSON stands for "JavaScript Object Notation", which can be said to be a "data format based on JavaScript language symbols". However, this notation is only based on JavaScript and can be used in various other languages.
JSON is a way we store and exchange data, implemented through its syntax, and used in many web applications. The advantage of JSON is that it has a human-readable format, which may be one of the reasons for using it in data transfer, in addition to its effectiveness when using APIs.
In JSON, data is represented by name/value pairs; objects are stored within curly brackets, each name is followed by ':' (colon), and name/value pairs are separated by (comma ) separated; square brackets enclose the array, with values separated by (comma).
Example of JSON format data:
{ "book1":{ "title": "Python Beginners", "year": 2005 , "page": 399 }, "book2":{ "title": "Python Developers", "year": 2006 , "page": 650 } }
Let’s take a closer look at how to process JSON data in Python.
Python makes processing JSON data easy. The module that achieves this is the json module. This module should be included in the Python (built-in) installation, so you don't need to install any external modules like you do with PDF and Excel files. To use this module, the only thing you need is to import it (start by writing):
import json
But what does the JSON library do? This library mainly parses JSON from files or strings. It also parses JSON to dictionary or list in Python and vice versa i.e. converts Python dictionary or list to JSON string.
Reading JSON (JSON to Python)
Reading JSON means converting JSON to Python values (objects). As mentioned above, the json library parses JSON into a dictionary or list in Python. For this we use loads() function (load from string) as shown below:
import json jsonData = '{"name": "Frank", "age": 39}' jsonToPython = json.loads(jsonData)
If you want to see the output, do print jsonToPython, in this case you will get the following output:
{'age': 39, 'name': 'Frank'}
That is, the data is returned as a Python dictionary (JSON object data structure).
Python to JSON
In the previous section we introduced JSON to Python, in this section we will show you how to convert Python values (encoded) as JSON.
Suppose we have the following dictionary in Python:
import json pythonDictionary = {'name':'Bob', 'age':44, 'isEmployed':True} dictionaryToJson = json.dumps(pythonDictionary)
If we run print dictionaryToJson, we get the following JSON data:
{"age": 44, "isEmployed": true, "name": "Bob"}
Therefore, this output is treated as an object ( Dictionary) data representation. The method dumps() is the key to this type of operation.
It should be noted at this time that JSON cannot store all types of Python objects, and can only store the following types: List; Dictionary; Boolean value; Number; String; None. Therefore, any other types need to be converted for storage in JSON.
Suppose we have the following class:
class Employee(object): def __init__(self, name): self.name = name
Suppose we create a new object abder as follows:
abder = Employee('Abder')
If we want to convert this object to JSON, the what to do? Is that json.dumps(abder)? In this case, you will receive an error similar to the following:
Traceback (most recent call last): File "test.py", line 8, in <module> abderJson = json.dumps(abder) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps return _default_encoder.encode(obj) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode return _iterencode(o, 0) File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: <__main__.Employee object at 0x10e74b750> is not JSON serializable
But, is there a workaround? Fortunately there is. To solve this problem, we can define a method similar to the following:
def jsonDefault(object): return object.__dict__
Then encode the object to JSON like this:
jsonAbder = json.dumps(abder, default=jsonDefault)
If you run print jsonAbder, you should get the following output :
{"name": "Abder"}
We have now encoded the Python object (abder) to JSON.
The above is the detailed content of How to process JSON data using Python. For more information, please follow other related articles on the PHP Chinese website!