В этом разделе показаны наиболее встречающиеся приемы работы с модулем json
.
JSONEncoder
json.tool
из bash для проверки JSON и красивого вывода>>> import json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) # '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print(json.dumps("\"foo\bar")) # "\"foo\bar" >>> print(json.dumps('\u1234')) # "\u1234" >>> print(json.dumps('\\')) # "\\" >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)) # {"a": 0, "b": 0, "c": 0} >>> from io import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() # '["streaming API"]'
>>> import json # простая сериализация >>> json.dumps([1, 2, 3, {'4': 5, '6': 7}]) # '[1, 2, 3, {"4": 5, "6": 7}]' # компактная сериализация >>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':')) # '[1,2,3,{"4":5,"6":7}]'
>>> import json >>> print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], sort_keys=True, indent=4)) # [ # 1, # 2, # 3, # { # "4": 5, # "6": 7 # } # ]
>>> import json >>> x = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') >>> x # ['foo', {'bar': ['baz', None, 1.0, 2]}] >>> x[0] # 'foo' >>> x[1] # {'bar': ['baz', None, 1.0, 2]} >>> x[1]['bar'] # ['baz', None, 1.0, 2] >>> x[1]['bar'][0] # 'baz' >>> x[1]['bar'][2] # 1.0 >>> json.loads('"\\"foo\\bar"') # '"foo\x08ar' >>> from io import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io) # ['streaming API']
>>> import json # Сначала создадим файл в формате JSON # что бы потом его прочитать >>> data = [ ... 'foo', ... {'bar': ['baz', None, 1.0, 2], ... 'key': 'value', ... '10': 'ten'}, ... [3, 4, 5, 6] ... ] # Открываем файл на запись >>> with open('data.json', 'w') as fp: # Преобразование объекта Python в данные # формата JSON, а так же запись в файл 'data.json' ... json.dump(data, fp) ... # теперь прочитаем данные из файла 'data.json' >>> with open('data.json', 'r') as fp: # Чтение файла 'data.json' и преобразование # данных JSON в объект Python ... data = json.load(fp) ... # Доступ к данным >>> data[0] # 'foo' >>> data[1]['bar'] # ['baz', None, 1.0, 2] >>> data[1]['bar'][2] # 1.0 >>> data[1]['10'] # 'ten' >>> data[2][3] # 6
>>> import json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) # (1+2j) >>> import decimal >>> json.loads('1.1', parse_float=decimal.Decimal) # Decimal('1.1')
JSONEncoder
:>>> import json >>> class ComplexEncoder(json.JSONEncoder): ... def default(self, obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... # Let the base class default method raise the TypeError ... return json.JSONEncoder.default(self, obj) ... >>> json.dumps(2 + 1j, cls=ComplexEncoder) # '[2.0, 1.0]' >>> ComplexEncoder().encode(2 + 1j) # '[2.0, 1.0]' >>> list(ComplexEncoder().iterencode(2 + 1j)) # ['[2.0', ', 1.0', ']']
json.tool
из bash для проверки JSON и красивого вывода:$ echo '["foo", {"bar": ["baz", null, 1.0, 2]}]' | python -m json.tool # [ # "foo", # { # "bar": [ # "baz", # null, # 1.0, # 2 # ] # } # ] $ echo '{1.2:3.4}' | python -m json.tool # Expecting property name enclosed in double quotes: line 1 column 2 (char 1)