JSON (JavaScript Object Notation) is a lightweight data exchange format. json module can be used in Python3 to encode and decode JSON data, which contains the following four functions:
Tip: File-like objects are objects that have a read() or write() method. For example, f = open('','r'), where f has a read() method, so f is a file-like object.
In the process of coding and decoding json, python's original type and JSON type will be converted to each other, the specific conversion control is as follows:
Table of Python encoded JSON type conversion equivalents:
Python | JSON |
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON decoding to Python type conversion table:
JSON | Python |
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
Example of operation :
import json data = { 'name': 'pengjunlee', 'age': 32, 'vip': True, 'address': {'province': 'GuangDong', 'city': 'ShenZhen'} } # Convert Python dictionary types to JSON objects json_str = (data) print(json_str) # results {"name": "pengjunlee", "age": 32, "vip": true, "address": {"province": "GuangDong", "city": "ShenZhen"}} # Convert JSON object types to Python dictionaries user_dic = (json_str) print(user_dic['address']) # results {'province': 'GuangDong', 'city': 'ShenZhen'} # Output Python dictionaries directly to a file with open('', 'w', encoding='utf-8') as f: (user_dic, f, ensure_ascii=False, indent=4) # Convert JSON strings in class file objects directly into Python dictionaries with open('', 'r', encoding='utf-8') as f: ret_dic = (f) print(type(ret_dic)) # Results <class 'dict'> print(ret_dic['name']) # in the end pengjunlee
Note: Using eval() enables simple conversions between strings and Python types.
user1 = eval('{"name":"pengjunlee"}') print(user1['name']) # in the end pengjunlee
to this article on the use of Python to parse JSON implementation examples of the article is introduced to this, more related Python to parse JSON content, please search for my previous posts or continue to browse the following articles hope that you will support me in the future!