JSON
a text serialization format
JSON, by default, can only represent a subset of the Python built-in types, and no custom classes
Unlike pickle, deserializing untrusted JSON does not in itself create an arbitrary code execution vulnerability
Serialize to File
import json
l = list(range(10))
# serialize to file
f = open('temp.json', 'w')
json.dump(l, f)
f.close()
# deserialize from file
f = open('temp.json', 'r')
print(json.load(f))
f.close()
Serialize to String
# serialize to string
s = json.dumps(l)
s = json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':')) # compact
s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) # pretty
# deserialize from string
json.loads(s)
JSON Class
# encode
encoder = json.JSONEncoder()
s = encoder.encode(l)
# decode
decoder = json.JSONDecoder()
decoder.decode(s)
Reference