环境信息
Python 中操作 json 相关格式,主要使用模块 json
Python 数据类型转换为 json 格式
python 数据类型转换为 json ,主要使用方法 dumps()
>>> adict = {'a': 1, 'b': 'st'} >>> json.dumps(adict) '{"a": 1, "b": "st"}'
>>> alist = [1,2,3,4] >>> json.dumps(alist) '[1, 2, 3, 4]'
|
json 格式转换为 Python 数据类型
>>> ajson = '[1, 2, 3, 4]' >>> type(ajson) <class 'str'>
>>> json.load(ajson) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.10/json/__init__.py", line 293, in load return loads(fp.read(), AttributeError: 'str' object has no attribute 'read'
>>> json.loads(ajson) [1, 2, 3, 4]
>>> bjson = '{"a": 1, "b": "st"}' >>> type(bjson) <class 'str'> >>> json.loads(bjson) {'a': 1, 'b': 'st'}
|