JSON (JavaScript Object Notation) Is a lightweight data exchange format .
If you don't already know JSON, You can read our JSON course .
Python3 Can be used in json Module to JSON Data encoding and decoding , It contains two functions :
json.dumps(): Code the data .
json.loads(): Decode the data .
stay json In the process of encoding and decoding ,Python The original type of json The types will switch to each other , The specific transformation contrast is as follows :
Python Encoded as JSON 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 Decoding for 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 example
The following example demonstrates Python The data structure is converted to JSON:
example (Python 3.0+)
#!/usr/bin/python3 import json # Python Dictionary type to JSON object data = { 'no' : 1, 'name' : 'Runoob', 'url' : 'http://www.runoob.com' } json_str = json.dumps(data) print ("Python Raw data :", repr(data)) print ("JSON object :", json_str)
The result of executing the above code is :
Python Raw data : {'url': 'http://www.runoob.com', 'no': 1, 'name': 'Runoob'}
JSON object : {"url": "http://www.runoob.com", "no": 1, "name": "Runoob"}
The output shows that , Simple types are encoded followed by their original repr() The output is very similar .
Then the above example , We can put a JSON The encoded string is converted back to a Python data structure :
example (Python 3.0+)
#!/usr/bin/python3 import json # Python Dictionary type to JSON object data1 = { 'no' : 1, 'name' : 'Runoob', 'url' : 'http://www.runoob.com' } json_str = json.dumps(data1) print ("Python Raw data :", repr(data1)) print ("JSON object :", json_str) # take JSON Object to Python Dictionaries data2 = json.loads(json_str) print ("data2['name']: ", data2['name']) print ("data2['url']: ", data2['url'])
The result of executing the above code is :
Python Raw data : {'name': 'Runoob', 'no': 1, 'url': 'http://www.runoob.com'}
JSON object : {"name": "Runoob", "no": 1, "url": "http://www.runoob.com"}
data2['name']: Runoob
data2['url']: http://www.runoob.com
If you're dealing with files instead of strings , You can use json.dump() and json.load() To code and decode JSON data . for example :
example (Python 3.0+)
# write in JSON data with open('data.json', 'w') as f: json.dump(data, f) # Reading data with open('data.json', 'r') as f: data = json.load(f)