JSON is a lightweight data exchange format. Most of the data returned by APIs are JSON and XML. If JSON is returned, the obtained data is converted into a dictionary. In terms of processing
python2.6 in the program, the JSON module has been added. The process of serialization and deserialization of python's json module are encoding and decoding, respectively.
encoding: Convert a python object encoding to a Json string.
decoding: Convert the json format string encoding into a python object.
python3 can use the json module to encode and decode json data, including the following two functions
json.dumps(): encode data
json.loads(): decode data
Example:
>>> import json
>>> data = {'num':100,'name':zhangsan}
>>> json_str = json.dumps(data) ##对数据进行编码
>>> print("Python data: " ,data)
Python data: {'num': 100, 'name': 'zhangsan'}
>>> print("JSON object: " ,json_str)
JSON object: {"num": 100, "name": "zhangsan"}
Use json.load to convert a json encoded string to a python data structure
instance:
>>> data = {'num':100,'name':'zhangsan'}
>>> json_str=json.dumps(data)
>> > json_str
'{"num": 100, "name": "zhangsan"}'
>>> data2=json.loads(json_str)
>>> data2
{'num': 100, 'name': 'zhangsan'}
If you are dealing with files instead of strings, you can use json.dump and json.load to process the data
json.dump() to store, json.load to read
Example
json.dump()
import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj) ##Write the list of numbers to number.json
json.load()
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)