Home > Backend Development > Python Tutorial > What are the common methods of Python json module?

What are the common methods of Python json module?

PHPz
Release: 2023-04-25 08:10:09
forward
1102 people have browsed it

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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template