HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a sub-set of ECMAScript.
Python3 json module can be used to encode and decode JSON data, which contains two functions:
In json codec process, python and json type of primitive types will be converted to each other, the specific transformation control as follows:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
The following example demonstrates Python data structures into JSON:
#!/usr/bin/python3 import json # Python 字典类型转换为 JSON 对象 data = { 'no' : 1, 'name' : 'w3resource', 'url' : 'https://w3resource.net' } json_str = json.dumps(data) print ("Python 原始数据:", repr(data)) print ("JSON 对象:", json_str)
Execute the above code output results:
Python 原始数据: {'url': 'https://w3resource.net', 'no': 1, 'name': 'w3resource'} JSON 对象: {"url": "https://w3resource.net/", "no": 1, "name": "w3resource"}
The results can be seen through the output, followed by the simple types by encoding its original repr () output is very similar.
Then the above example, we can convert a JSON-encoded string back to a Python data structure:
#!/usr/bin/python3 import json # Python 字典类型转换为 JSON 对象 data1 = { 'no' : 1, 'name' : 'w3resource', 'url' : 'https://w3resource.net' } json_str = json.dumps(data1) print ("Python 原始数据:", repr(data1)) print ("JSON 对象:", json_str) # 将 JSON 对象转换为 Python 字典 data2 = json.loads(json_str) print ("data2['name']: ", data2['name']) print ("data2['url']: ", data2['url'])
Execute the above code output results:
ython 原始数据: {'name': 'w3resource', 'no': 1, 'url': 'https://w3resource.net'} JSON 对象: {"name": "w3resource", "no": 1, "url": "https://w3resource.net/"} data2['name']: w3resource data2['url']: https://w3resource.net
If you want to deal with is the file instead of a string, you can usejson.dump () and json.load ()to encode and decode JSON data. E.g:
# 写入 JSON 数据 with open('data.json', 'w') as f: json.dump(data, f) # 读取数据 with open('data.json', 'r') as f: data = json.load(f)
For more information, please refer to: https://docs.python.org/3/library/json.html