How to use Python's json standard library

PHPz
Release: 2023-06-03 12:25:59
forward
1294 people have browsed it

1. Overview of JSON basics

1. What is JSON?

JSON(full name: JavaScript Object Notation object notation) is a lightweight text data exchange format. The data format of JSON is actually the dictionary format in python , which can contain arrays enclosed in square brackets, which are lists in python.

  • JSON is language independent

  • JSON is self-descriptive and easier to understand

  • JSON than XML is smaller, faster, and easier to parse

  • Crawlers often obtain interface data, which is in JSON format

2. JSON long What does it look like?

Grammar format:{key1:value1, key2:value2,}Key-value pair format (separated by colon), use commas to connect the pairs

Simple case: JSON object

{ "name": "小明", "age": 18}
Copy after login

Complex case: JSON array

{ "student": [ {"name": "小明", "age": 11}, {"name": "小红","age": 10} ], "classroom": {"class1": "room1", "class2": "room2"}}
Copy after login

3. Notes

1. The key part of the key-value pair of json must be wrapped in double quotes", single quotes will not work (so if keywords appear in the key, they will also be characterized), and objects in js are not mandatory Requirements (so keywords are not allowed in the key).

2. The value part of the key-value pair of json is not allowed to have function, undefined, NaN, but it can have null, the value of the object in js can appear in.

3. After the json data ends, meaningless commas are not allowed to appear, such as:{"name":"admin","age":18,}, Pay attention to the comma after 18 at the end of the data, which is not allowed.

4. Summary of json format

The correct json format is as follows:

# 格式1:JSON 对象{"name": "admin", "age": 18}# 格式2:JSON 数组{ "student": [ {"name": "小明", "age": 18}, {"name": "小红", "age": 16}, {"name": "小黑", "age": 20} ]}
Copy after login

The wrong json format is as follows:

2. json module

1. Function

1. Use jsON string to generate python object (load)

2. Format the python object into ison string (dump)

2. Data Type conversion

Converts data fromPython to jsonformat. There will be changes in data type, as shown in the following table:

##dict object list, tuple array str string int, float, int- & float-derived Enums number True true ##False None In turn, convert the json format into python built-in types, as shown in the following table:
Python JSON
false
null

JSON ##object dict array list string str number(int) int number(real) float true True false False None 3. Usage method The use of the json module is actually very simple. For most situations, we only need to use the following four methods:
Python
##null

Method

4、 json.dumps()

将python数据类型转换为json格式的字符串。

语法格式json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

>>> import json # Python字典 >>> person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True} >>> print(person) {'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True} >>> type(person) >> jsonStr = json.dumps(person) >>> print(jsonStr ) {"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true} >>> type(jsonStr) 
Copy after login

从上可以看出json格式和Python格式的区别在于:python格式打印输出是单引号,类型为dict。而json格式打印输出是双引号,类型为:strTrue的开头大小写区别。

使用参数能让JSON字串格式化输出:

>>> print(json.dumps(person, sort_keys=True, indent=4, separators=(',', ': '))){ "age": 30, "isonly": true, "name": "\u5c0f\u660e", "tel": [ "888888", "1351111111" ]}
Copy after login

参数解读

  • sort_keys:是否排序

  • indent:定义缩进距离

  • separators:是一个元组,定义分隔符的类型

  • skipkeys:是否允许JSON字串编码字典对象时,字典的key不是字符串类型(默认是不允许)

修改分割符类型

>>> print(json.dumps(person, sort_keys=True, indent=4, separators=('!', '-'))){ "age"-30! "isonly"-true! "name"-"\u5c0f\u660e"! "tel"-[ "888888"! "1351111111" ]
Copy after login

文件操作

import json person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}jsonStr = json.dumps(person)with open('test.json', 'w', encoding='utf-8') as f: # 打开文件 f.write(jsonStr) # 在文件里写入转成的json串
Copy after login

查看生成的新文件:

5、json.dump()

将python数据类型转换并保存到son格式的文件内。

语法格式json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

import json person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}json.dump(person, open('data.json', 'w'))
Copy after login

查看生成的新文件:

使用参数能让JSON字串格式化输出:

import json person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}json.dump(person, open('data.json', 'w'), sort_keys=True, indent=4, separators=(',', ': '))
Copy after login

再次查看文件:

json.dumpsjson.dump写入文件的区别

  • dump() 不需要使用.write()方法,只需要写那个字典,那个文件即可;而 dumps() 需要使用.write()方法写入。

  • 如果把字典写到文件里面的时候,dump()好用;但是如果不需要操作文件,或需要把内容存储到数据库何excel,则需要使用dumps()先把字典转换成字符串,再写入

6、json.loads()

将json格式的字符串转换为python的类型。

语法格式json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

>>> import json# Python字典>>> person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}>>> print(person){'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}>>> type(person)>> jsonStr = json.dumps(person) >>> print(jsonStr ){"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true}>>> type(jsonStr)# json字符串再转换为Python字典>>> python_obj = json.loads(jsonStr)>>> print(python_obj){'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}>>> print(type(python_obj))# 打印字典的所有key>>> print(python_obj.keys()) dict_keys(['name', 'age', 'tel', 'isonly']) # 打印字典的所有values>>> print(python_obj.values()) dict_values(['小明', 30, ['888888', '1351111111'], True])
Copy after login

文件操作:

import json f = open('data.json', encoding='utf-8')content = f.read() # 使用loads()方法需要先读文件 python_obj = json.loads(content)print(python_obj)
Copy after login

输出结果:

7、json.load()

从json格式的文件中读取数据并转换为python的类型。

语法格式json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

文件操作

import json python_obj = json.load(open('data.json','r'))print(python_obj)print(type(python_obj))
Copy after login

输出结果:

json.load()json.loads()区别:

  • loads() 传的是json字符串,而 load() 传的是文件对象

  • 使用 loads() 时需要先读取文件在使用,而 load() 则不用

8、总结

不管是dump还是load,带s的都是和字符串相关的,不带s的都是和文件相关的

三、XML文件和JSON文件互转

记录工作中常用的一个小技巧

cmd控制台安装第三方模块

pip install xmltodict
Copy after login

1、XML文件转为JSON文件

新建一个1.xml文件:

 tom mary love
Copy after login

转换代码实现

import jsonimport xmltodictdef xml_to_json(xml_str): """parse是的xml解析器,参数需要 :param xml_str: xml字符串 :return: json字符串 """ xml_parse = xmltodict.parse(xml_str) # json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。 # dumps()方法的ident=1,格式化json json_str = json.dumps(xml_parse, indent=1) return json_str XML_PATH = './1.xml' # xml文件的路径with open(XML_PATH, 'r') as f: xmlfile = f.read() with open(XML_PATH[:-3] + 'json', 'w') as newfile: newfile.write(xml_to_json(xmlfile))
Copy after login

输出结果(生成json文件):

2、JSON文件转换为XML文件

新建test.json文件:

{ "student": { "course": { "name": "math", "score": "90" }, "info": { "sex": "male", "name": "name" }, "stid": "10213" }}
Copy after login

转换代码实现:

import xmltodictimport jsondef json_to_xml(python_dict): """xmltodict库的unparse()json转xml :param python_dict: python的字典对象 :return: xml字符串 """ xml_str = xmltodict.unparse(python_dict) return xml_str JSON_PATH = './test.json' # json文件的路径with open(JSON_PATH, 'r') as f: jsonfile = f.read() python_dict = json.loads(jsonfile) # 将json字符串转换为python字典对象 with open(JSON_PATH[:-4] + 'xml', 'w') as newfile: newfile.write(json_to_xml(python_dict))
Copy after login

输出结果(生成xml文件):

The above is the detailed content of How to use Python's json standard library. 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!
Function ##json.dumps(obj) Convert python data type to json format string. Convert python data type and save it to a file in son format. Convert json format string to python type. Read data from a json format file and convert it to python type.
json.dump(obj, fp)
json.loads(s)
json.load(fp)