字典定义:dict是python中一种常用的数据类型,以关键字为索引,关键字可以是任意不可变类型,通常用字符串或数值,如果元组中只包含字符串和数字,它可以作为关键字,理解字典的最佳方式是把它看作无需的键值对(key:value)集合,键必须是唯一的。
json (JavaScrtpt Object Notation):由RFC 7159(which obsoletesRFC 4627) 和ECMA-404指定,是一个受JavaScript的对象字面量语法启发的轻量级数据交换格式。
dict 转json 字符串:
dumps:将_obj_序列化为JSON格式的[`str`]。
import json
test_dict = {'name': 'tfz', 'age': 18, 'sex': 'male'}
dict_to_json_str = json.dumps(test_dict)
print(dict_to_json_str)
# {"name": "tfz", "age": 18, "sex": "male"}
print(type(dict_to_json_str))
#
序列化obj为一个JSON格式的流并输出到fp
import json
test_dict = {'name': 'tfz', 'age': 18, 'sex': 'male', '中文': '值'}
with open("./tfz.json", mode="w", encoding='utf-8') as f:
json.dump(test_dict, f, ensure_ascii=False)

读取一个json文件并转化为一个json对象
"""将fp(一个支持`.read()`并包含一个JSON文档的[text file]或者[binary file] 反序列化为一个 Python 对象。"""
import json
with open('./tfz.json', mode='r', encoding='utf-8') as fp:
json_obj = json.load(fp)
print(json_obj)
print(type(json_obj))

序列化 s (a[str
],[bytes
])or[bytearray
]instance containing aJSONdocument) 为python对象
import json
test_dict = [{'name': 'tfz', 'age': 18, 'sex': 'male', '中文': '值'}]
json_str = json.dumps(test_dict, ensure_ascii=False)
js = json.loads(json_str, encoding='utf-8')
print(js)
print(type(js))
# 序列化一个实例对象
import json
class Computer(object):
def __init__(self, name, price):
self.name = name
self.price = price
def serialize_instance(obj):
d = {'__class_name__': type(obj).__name__}
d.update(vars(obj))
return d
computer = Computer("tfz", 10086)
c = json.dumps(computer, default=serialize_instance)
print(c)

获取序列化后的实例对象
classes = {
"Computer": Computer
}
def unserialize_instance(d):
cls_name = d.pop('__class_name__', None)
if cls_name:
_cls = classes[cls_name]
# make instance without calling __init__
obj = _cls.__new__(_cls)
for key, value in d.items():
setattr(obj, key, value)
return obj
else:
return d
unserialize_c = json.loads(c, object_hook=unserialize_instance)
print(unserialize_c)
print(type(unserialize_c))
