Home Backend Development Python Tutorial How to process JSON data using Python

How to process JSON data using Python

Nov 14, 2018 pm 02:37 PM
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
 }
}
Copy after login

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
Copy after login

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)
Copy after login

If you want to see the output, do print jsonToPython, in this case you will get the following output:

{'age': 39, 'name': 'Frank'}
Copy after login

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)
Copy after login

If we run print dictionaryToJson, we get the following JSON data:

{"age": 44, "isEmployed": true, "name": "Bob"}
Copy after login

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
Copy after login

Suppose we create a new object abder as follows:

abder = Employee('Abder')
Copy after login

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
Copy after login

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__
Copy after login

Then encode the object to JSON like this:

jsonAbder = json.dumps(abder, default=jsonDefault)
Copy after login

If you run print jsonAbder, you should get the following output :

{"name": "Abder"}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles