Python3 JSON data analysis
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:
- json.dumps (): encoding data.
- json.loads (): data is decoded.
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 encoded as a type conversion correspondence table:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON decodes the Python type conversion correspondence table:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
json.dumps and json.loads examples
The following example demonstrates Python data structures into JSON:
#!/usr/bin/python3 import json # Python 字典类型转换为 JSON 对象 data = { 'no' : 1, 'name' : 'w3big', 'url' : 'http://www.w3write.com' } json_str = json.dumps(data) print ("Python 原始数据:", repr(data)) print ("JSON 对象:", json_str)
Execute the above code output results:
Python 原始数据: {'url': 'http://www.w3write.com', 'no': 1, 'name': 'w3big'} JSON 对象: {"url": "http://www.w3write.com", "no": 1, "name": "w3big"}
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' : 'w3big', 'url' : 'http://www.w3write.com' } 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': 'w3big', 'no': 1, 'url': 'http://www.w3write.com'} JSON 对象: {"name": "w3big", "no": 1, "url": "http://www.w3write.com"} data2['name']: w3big data2['url']: http://www.w3write.com
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