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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles