dict和json格式转换

2019-01-22  本文已影响0人  一平曲

同时解决: TypeError: Object of type 'bytes' is not JSON serializable

默认的编码函数很多数据类型都不能编码,因此可以自己写一个encoder去继承jsonencoder ,这样就能够进行编码了

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(MyEncoder, self).default(obj)

dict to json

def dict_to_json(dict_obj,name, Mycls = None):
    
    js_obj = json.dumps(dict_obj, cls = Mycls, indent=4)
    
    with open(name, 'w') as file_obj:
        file_obj.write(js_obj)

json to dict

def json_to_dict(filepath, Mycls = None):
    with open(filepath,'r') as js_obj:
        dict_obj = json.load(js_obj, cls = Mycls)
    return dict_obj
上一篇下一篇

猜你喜欢

热点阅读