Python Data Conversion JSON
Import JSON # Imports 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) # Converts an object to a string, like Java's ToString () eval (str) # Converts a repr () converted string into an object
JSON Read and write
# Write JSON data with open (' Data1.json ', ' W ') as F: json.dump (data, f) # Read data with open (' Data1.json ', ' R ') as F: data = j Son.load (f)
Summarize:
Data conversion
First step: Introducing the JSON package: Import JSON
Step Two: Use Json.dumps (pythonobj) to convert Python data to JSON data
Step Three: Use Json.loads (jsonobj) to convert JSON data to Python data
File Write read
Write using Dump
Read with load
Python and JSON data are converted to each other, repr and eval () use