https://docs.python.org/3/library/json.html # 该module总是产生str对象,而不是bytes对象。 import json """ Encoding """ # json.dump(obj, fp, ......): 将obj作为一个JSON-formatted stream序列化到fp(a .write()-supporting file-like object)。 因为json模块产生的是str对象,所以fp.write() must support str input. from io import StringIO io = StringIO() json.dump(['streaming API'], io) io.getvalue() # return: '["streaming API"]' # json.dumps(obj, *, .......): 将obj作为一个JSON-formatted str进行序列化 json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':')) json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) """ Decoding """ # json.load(fp, *, ......): 解序列化fp (a .read()-supporting text file or binary file containing a JSON document) 到一个Python对象 from io import StringIO io = StringIO('["streaming API"]') json.load(io) with open(filepath, 'r') as jsonfile: jsonobj = json.load(jsonfile) # json.loads(s, ......): Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') |