Conversion of python and json data, reading and writing of json data, use of repr and eval (), and use of jsonrepr
Python data conversion json
Import json # import json package data = [{"id": 1, "username": "zhangshan", "password": "123qwe", "lock": True }, {"id": 2, "username": "lisi", "password": "123qwe", "lock": True}, {"id": 3, "username": "wangwu", "password": "123qwe", "lock": False}] jsonStr = json. dumps (data) # json data print (jsonStr) # python data print ('raw data string: ', repr (jsonStr ))
Convert json to pathon data
pyStr = json.loads(jsonStr)print(pyStr)
Repr and eval usage
Repr (object) # convert an object to a string, similar to java's toString () eval (str) # convert repr () to an object
Json reading and writing
# Write JSON data with open ('data1. json ', 'w') as f: json. dump (data, f) # Read data with open ('data1. json ', 'R') as f: data = json. load (f)
Summary:
Data Conversion
Step 1: Introduce the json package: import json
Step 2: Use json. dumps (pythonObj) to convert python data to json data
Step 3: Use json. loads (jsonObj) to convert json data to python data
File write and read
Use dump to write data
Use load to read