Table of Contents
jons.loads()
json.dump()
json.load()
json.dumps()
JSON method summary
Home Backend Development Python Tutorial What are the common methods of Python json module?

What are the common methods of Python json module?

Apr 25, 2023 am 08:10 AM
python json

JSON (JavaScript Object Notation) is a lightweight data exchange format that follows the JavaScript specification established by the European Computer Association (referred to as ECMAScript).

JSON is easy for people to read and write, and it is also easy for machines to parse and generate. It can effectively improve the transmission efficiency of network information. Therefore, it is often used as a standard language for transmitting information between networks and programs, such as clients. Information interaction with the server is transmitted in JSON format.

Simply put, JSON can convert a set of data represented by JavaScript objects into a string format to facilitate the transmission of this string over the network and between programs. And when needed, it can also be converted into a data format supported by the programming language. This section mainly introduces how to implement conversion between JSON data and Python data types.

The Python language has a built-in module that specializes in processing JOSN data - the jons module. Through this module, the conversion between JSON and Python data formats can be completed.

jons.loads()

This method can convert json format strings into Python objects (such as lists, dictionaries, tuples, integers and floating point types), which are the most commonly used is converted to dictionary type. The example is as follows:

# coding:utf8
import json
#JOSN字符串
website_info='{"name" : "CSDN","PV" : "2000万","UV" : "800万","create_time" : "1999年"}'
py_dict=json.loads(website_info)
print("python字典数据格式:%s;数据类型:%s"% (py_dict,type(py_dict)))
Copy after login

Output result:

python dictionary data format: {'name': 'CSDN', 'PV': '20 million', 'UV': ' 8 million', 'create_time': '1999'}; Data type:

Note: The JSON string in the above example looks very similar to the Python dictionary. But its essence is different. JOSN is a string type, while Python dictionary is a dict type.

json.dump()

It can convert Python objects (dictionaries, lists, etc.) into json strings, and write the converted data to json format files, so This method must operate on a file stream object. For example, after using a crawler program to complete data capture, sometimes it is necessary to save the data in json format. In this case, the json.dump() method is used. The syntax format is as follows:

json.dump(object,f,inden=0,ensure_ascii=False)
Copy after login

The parameter description is as follows:

  • object: Python data object, such as dictionary, list, etc.

  • f: File stream object, that is, file handle.

  • indent: Format stored data to make JSON strings easier to read.

  • ensure_ascii: Whether to use ascii encoding. When Chinese appears in the data, it needs to be set to False.

Example Example is as follows:

import json
ditc_info={"name" : "CSDN","PV" : "2000万","UV" : "800万","create_time" : "1999年"}
with open("web.josn","a") as f:
    json.dump(ditc_info,f,ensure_ascii=False)
Copy after login

Open the web.json file, its content is as follows:

{
"name": "CSDN",
"PV": "2000万",
"UV": "800万",
"create_time": "1999年"
}
Copy after login

You can also convert the Python list into JSON string and save it to a json file, as shown below:

import json
item_list = []
item = {'website': 'CSDN', 'url': "www.CSDN.net"}
for k,v in item.items():
    item_list.append(v)
with open('info_web.json', 'a') as f:
    json.dump(item_list, f, ensure_ascii=False)
Copy after login

Open the info_web.json file, its content is as follows:

["CSDN", "www.CSDN .net"]

json.load()

This method is used to operate file stream objects, but it is just the opposite of dump(). It means reading from a json file JSON string and convert the read content into a Python object. Usage examples are as follows:

import json
site = {'name':'CSDN',"url":"www.CSDN.net"}
filename = 'website.json'
with open (filename,'w') as f:
    json.dump(site,f,ensure_ascii=False)
with open (filename,'r') as f:
    print(json.load(f))
Copy after login

The output results are as follows:

{'name': 'CSDN', 'url': 'www.CSDN.net'}

json.dumps()

This method can convert Python objects into JSON strings. An example is as follows:

import json
#python字典
item = {'website': 'CSDN', 'rank': 1}
# json.dumps之后
item = json.dumps(item,ensure_ascii=False)
print('转换之后的数据类型为:',type(item))
print(item)
Copy after login

The output result is as follows:

The data type after conversion is:
{"website": "CSDN", "url": "www.CSDN.net"}

Finally, make a brief summary of the above methods, as shown in the following table:

JSON method summary

Method Function
json.dumps() Convert Python objects into JSON strings.
json.loads() Convert JSON string to Python object.
json.dump() Convert objects in Python into JSON strings and store them in files.
json.load() Convert the JSON string in the file into a Python object and extract it.

In summary, json.load() and json.dump() operate on file stream objects and realize the reading and writing operations of json files, while json.loads () and json.dumps() operate on Python objects or JOSN strings.

The above is the detailed content of What are the common methods of Python json module?. 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
4 weeks 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)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Can Python parameter annotations use strings? Can Python parameter annotations use strings? Apr 01, 2025 pm 08:39 PM

Alternative usage of Python parameter annotations In Python programming, parameter annotations are a very useful function that can help developers better understand and use functions...

How do Python scripts clear output to cursor position at a specific location? How do Python scripts clear output to cursor position at a specific location? Apr 01, 2025 pm 11:30 PM

How do Python scripts clear output to cursor position at a specific location? When writing Python scripts, it is common to clear the previous output to the cursor position...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

How to use Python and OCR technology to try to crack complex verification codes? How to use Python and OCR technology to try to crack complex verification codes? Apr 01, 2025 pm 10:18 PM

Exploration of cracking verification codes using Python In daily network interactions, verification codes are a common security mechanism to prevent malicious manipulation of automated programs...

Do Google and AWS provide public PyPI image sources? Do Google and AWS provide public PyPI image sources? Apr 01, 2025 pm 05:15 PM

Many developers rely on PyPI (PythonPackageIndex)...

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

See all articles