1.基础模块-json 模块案例

class Use_json(object):
    
    def read_json(self, name):
        '''
        
        :param name: ./data.json
        :return: 
        '''
        with open(name, 'r') as f:
            data_back = json.load(f, strict=False, encoding='utf-8')
            return data_back
    
    
    def save_josn(self, name, data):
        '''
    
        :param name: /data.json
        :param data:
        :return:
        '''
        json_str = json.dumps(data, indent=4, separators=(',', ': '))
        print(json_str)
        import os
        filename = name  # r'./data.json'
        if os.path.exists(filename):
            print('已存在json文件,追加')
            with open(filename, 'r', encoding='utf8') as history_file:
                history_file_list = json.load(history_file)
            with open(filename, 'w+', encoding='utf8') as history_file_write:
                new_order = {}
                history_file_list.append(new_order)
                history_file_write.write(json.dumps(history_file_list, ensure_ascii=False))
        else:
            print('无json文件创建。。。')
            new_order_list = []
            new_order = {}
            new_order_list.append(new_order)
    
            with open(filename, 'w+', encoding='utf8') as f:
                f.write(json_str)

posted @ 2021-01-20 11:17  鲁哒哒  阅读(35)  评论(0编辑  收藏  举报