Table of Contents
orjson common methods
1. Serialization
2. Deserialization
3. Rich option option
4. Add custom processing strategies for dataclass and datetime
Home Backend Development Python Tutorial Third-party JSON libraries worth learning in Python

Third-party JSON libraries worth learning in Python

Apr 11, 2023 pm 08:49 PM
python json

In our daily use of Python, we often use json format to store some data, especially in web development. However, Python's native json library has poor performance and few functions, and can only cope with simple and lightweight json data storage and conversion needs.

Third-party JSON libraries worth learning in Python

The third-party json library orjson I want to introduce to you in this article has a performance advantage of several times to dozens of times in various public benchmark performance tests. It compresses other Python libraries such as json, ujson, rapidjson, simplejson, etc., and has many additional functions. Let’s take a look at its common methods~

orjson common methods

orjson supports all 3.7 to 3.10 For 64-bit version of Python, the orjson version demonstrated in this article is 3.7.0. You can directly use pip install -U orjson to complete the installation. Let's demonstrate the common methods in orjson:

1. Serialization

Similar to the native json library, we can use orjson.dumps() to serialize Python objects into JSON data , note that the slight difference is that the result of orjson serialization is not str type but bytes type. In the following example, we serialize a list containing 10 million simple dictionary elements. The difference between orjson and json libraries The time-consuming comparison is as follows:

Third-party JSON libraries worth learning in Python

2. Deserialization

The process of converting JSON data into Python objects is called deserialization, using orjson .loads() operates and accepts common types such as bytes and str. Based on the previous examples, we add deserialization examples:

Third-party JSON libraries worth learning in Python

3. Rich option option

In the serialization operation of orjson, many additional functions can be configured through the parameter option. Commonly used ones are:

(1) OPT_INDENT_2

By configuring option= orjson.OPT_INDENT_2, we can add a 2-space indent beautification effect to the serialized JSON result to make up for the lack of parameter indent:

Third-party JSON libraries worth learning in Python

(2) OPT_OMIT_MICROSECONDS

orjson.dumps() can directly convert date and time objects in standard libraries such as datetime and time in Python into corresponding strings. This is something that the native json library cannot do. By configuring option= orjson.OPT_OMIT_MICROSECONDS, you can omit the millisecond part of the suffix of the conversion result:

Third-party JSON libraries worth learning in Python

(3) OPT_NON_STR_KEYS

When the object to be serialized has a non-numeric type When using keys, orjson will throw a TypeError by default. In this case, you need to configure option=orjson.OPT_NON_STR_KEYS to force the conversion of these keys into character types:

Third-party JSON libraries worth learning in Python

##(4) OPT_SERIALIZE_NUMPY

An important feature of orjson is that it can convert complex objects containing data structure objects in numpy into arrays in JSON with compatibility, just with option=orjson.OPT_SERIALIZE_NUMPY:

Third-party JSON libraries worth learning in Python

(5) OPT_SERIALIZE_UUID

In addition to automatically serializing numpy objects, orjson also supports conversion of UUID objects. In versions before orjson 3.0, option=orjson is required. .OPT_SERIALIZE_UUID, and the 3.X version demonstrated in this article does not require additional configuration parameters:

Third-party JSON libraries worth learning in Python

(6) OPT_SORT_KEYS

By matching the parameter option=orjson.OPT_SORT_KEYS , the serialized results can be automatically sorted by key:

Third-party JSON libraries worth learning in Python

(7) Combine multiple options

when your serialization operation needs to involve When using multiple option functions, you can use the | operator to combine multiple option parameters:

Third-party JSON libraries worth learning in Python

4. Add custom processing strategies for dataclass and datetime

When the objects you need to serialize involve dataclass custom data structures, you can cooperate with orjson. OPT_PASSTHROUGH_DATACLASS, and then pass the default parameter into a custom processing function to achieve more free data conversion logic. For example, in the following simple example, we can use this feature to desensitize the original data:

Third-party JSON libraries worth learning in Python

Similarly, for datetime type data, we can also cooperate with OPT_PASSTHROUGH_DATETIME and custom default functions to implement date custom format conversion:

Third-party JSON libraries worth learning in Python

For more features of orjson, please go to the official warehouse https://github.com/ijl/orjson to learn more.

The above is the detailed content of Third-party JSON libraries worth learning in 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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

Is There an RSS Alternative Based on JSON? Is There an RSS Alternative Based on JSON? Apr 10, 2025 am 09:31 AM

JSONFeed is a JSON-based RSS alternative that has its advantages simplicity and ease of use. 1) JSONFeed uses JSON format, which is easy to generate and parse. 2) It supports dynamic generation and is suitable for modern web development. 3) Using JSONFeed can improve content management efficiency and user experience.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to view server version of Redis How to view server version of Redis Apr 10, 2025 pm 01:27 PM

Question: How to view the Redis server version? Use the command line tool redis-cli --version to view the version of the connected server. Use the INFO server command to view the server's internal version and need to parse and return information. In a cluster environment, check the version consistency of each node and can be automatically checked using scripts. Use scripts to automate viewing versions, such as connecting with Python scripts and printing version information.

See all articles