JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript.
The JSON module can be used to encode JSON data in Python3, which contains two functions:
- json.dumps (): encodes the data.
- json.loads (): decodes the data.
In the JSON encoding and decoding process, the original Python type and JSON type will be converted to each other, the specific conversions against the following:
Python encoding is a JSON type conversion 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 corresponding table for the Python type conversion:
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 instances
The following example demonstrates the conversion of a PYTHON data structure to JSON:
#!/usr/bin/python3import json# Python dictionary type converted to JSON object data = { ' no ': 1, ' name ': ' W3cschool ', ' url ': '/http ' www.w3cschool.cn '}json_str = json.dumps (data) print ("Python raw Data:", repr (data)) print ("JSON object:", Json_str)
Execute the above code to output the result:
Python raw data: {' URL ': ' http://www.w3cschool.cn ', ' No ': 1, ' name ': ' W3cschool '}json object: {' URL ': ' http://www.w3cschool.cn ', "No": 1, "name": "W3cschool"}
The result of the output shows that the simple type is very similar by encoding followed by its original repr () output.
Next, we can convert a JSON-encoded string back to a python data structure:
#!/usr/bin/python3import json# Python dictionary type converted to JSON object data1 = { ' no ': 1, ' name ': ' W3cschool ', ' url ': ' http:/ /www.w3cschool.cn '}json_str = Json.dumps (data1) print ("Python raw Data:", repr (data1)) print ("JSON object:", JSON_STR) # will JSON object Convert to Python dictionary data2 = json.loads (json_str) print ("data2[' name ']:", data2[' name ']) print ("data2[' url ']:", data2[' url '))
Execute the above code to output the result:
Ython raw data: {' name ': ' W3cschool ', ' No ': 1, ' url ': ' http://www.w3cschool.cn '}json object: {' name ': ' W3cschool ', ' No ': 1, ' URL ': "http://www.w3cschool.cn"}data2[' name ': w3cschooldata2[' url ']: http://www.w3cschool.cn
If you are dealing with files instead of strings, you can use json.dump () and json.load () to encode and decode JSON data. For example:
# Write JSON data with open (' Data.json ', ' W ') as F: json.dump (data, f) # Read data with open (' Data.json ', ' R ') as F: data = JSO N.load (f)
Python3 JSON Data parsing