Python Json操作封裝的基本實現

2021-08-19 11:16:30 字數 4875 閱讀 9473

#!/usr/bin/env python3

# -*- coding= utf-8 -*-

# name=jsonconfig

# version=0.0.1

# packages=

# author=singebogo

# [email protected]

# date=20180427

import json, demjson

from new_frame.api.filegener.fileoperator.filebase import filebase

from new_frame.api.exception.filenotfound import filenotfounderror

from new_frame.util.logutil.log import logger

class jsonconfig(object):

'''1、對json進行序列化,反序列化,一次性的dump和load持久化檔案  

2、 #自定義資料型別的序列化/反序列化

#要實現自定義資料型別的序列化與反序列化有兩種方式:

# 1、通過轉換函式實現

# 2、通過繼承jsonencoder和jsondecoder類實現

'''def __init__(self,file=none, dict={}):

self.dict = dict

self.file = file

# 序列化

def dumps(self, dict={}):

try:

if dict is none:

return json.dumps(self.dict)

else:

return json.dumps(dict)

except baseexception as baseerr:

logger.error(baseerr.message)

print (baseerr.message)

# 反序列化

def loads(self, dict={}):

try:

if dict is none:

return json.loads(self.dict)

else:

return json.loads(dict)

except baseexception as baseerr:

logger.error(baseerr.message)

print (baseerr.message)

# 序列化到檔案中

def write(self, dict={}, mode='w',indent=4):

'''@param mode:檔案開啟模式 預設引數為w

@param indent:

@param dict: 需要dump的字典

@return:返回none json寫入檔案成功

'''if self.file is not none:

with open(self.file, mode) as fp:

if dict is none:

return json.dump(self.dict, fp, indent)

else:

return json.dump(dict, fp, indent)

# 反序列化檔案中的內容

def read(self, mode = 'r'):

'''@param mode: 檔案開啟模式 預設引數為r

@return:返回dict

'''if self.file is not none:

if filebase(self.file).i***ist(none):

try:

with open(self.file, mode) as fp:

return json.load(fp)

except oserror as oserr:

print (oserr)

logger.error(oserr.message + "json read error")

else:

logger.error(self.file + "not exits")

raise filenotfounderror(self.file + "not exits")

# 自定義資料型別的序列化/反序列化

# 方法1:編寫轉換函式

'''def obj2dict(obj):

d = {}

d['__class__'] = obj.__class__.__name__

d['__module__'] = obj.__module__

d.update(obj.__dict__)

return d

def dict2obj(d):

if '__class__' in d:

class_name = d.pop('__class__')

module_name = d.pop('__module__')

module = __import__(module_name)

class_ = getattr(module, class_name)

args = dict((key.encode('ascii'), value) for key, value in d.items())

instance = class_(**args)

else:

instance = d

return instance

'''#方法2 繼承jsonencoder和jsondecoder實現子類

class myjsonencoder(json.jsonencoder):

def default(self, obj):

d = {}

d['__class__'] = obj.__class__.__name__

d['__module__'] = obj.__module__

d.update(obj.__dict__)

return d

class myjsondecoder(json.jsondecoder):

def __init__(self):

json.jsondecoder.__init__(self, object_hook=self.dict2obj)

def dict2obj(self, d):

if '__class__' in d:

class_name = d.pop('__class__')

module_name = d.pop('__module__')

module = __import__(module_name)

class_ = getattr(module, class_name)

args = dict((key.encode('ascii'), value) for key, value in d.items())

instance = class_(**args)

else:

instance = d

return instance

if __name__ == '__main__':

class student(object):

def __init__(self, name, age, sno):

self.name = name

self.age = age

self.sno = sno

def __repr__(self):

return 'student [name: %s, age: %d, sno: %d]' % (self.name, self.age, self.sno)

jsonconfig = jsonconfig('test.json', )

print (jsonconfig.write())

encode = jsonconfig.read()

print (jsonconfig.dumps()) #空字典

decode = jsonconfig.dumps(encode)

print (jsonconfig.loads()) #空字典

print (jsonconfig.loads(decode))

stu = student('tom', 19, 1)

#方式一:直接呼叫子類myjsonencoder的encode()方法進行序列化

print (jsonconfig.myjsonencoder().encode(stu))

print (jsonconfig.myjsonencoder(separators=(',', ':')).encode(stu))

# 方式二:將子類myjsonencoder作為cls引數的值傳遞給json.dumps()函式

objencode = json.dumps(stu, cls=jsonconfig.myjsonencoder)

print ("---------------------")

print (jsonconfig.write(objencode))

print (json.dumps(stu, cls=jsonconfig.myjsonencoder, separators=(',', ':')))

# 反序列化測試:

print (jsonconfig.myjsondecoder().decode(''))

print (jsonconfig.myjsondecoder().decode(objencode))

print (jsonconfig.read())

Python JSON 基本操作

python version 3.4.4 測試資料 import json aa bb json模組提供的函式 json.dumps 和 json.loads 輸出 print bb data json.dumps bb print data load json.loads data print l...

python json轉化操作

usr bin python coding utf 8 import json import sys import os 重要函式 編碼 把乙個python物件編碼轉換成json字串 json.dumps 解碼 把json格式字串解碼轉換成python物件 json.loads def test00...

Python json模組的使用

資料的分類 非結構化的資料 html等 處理方式 正規表示式,xpath 結構化資料 json,xml 處理方法 轉換為python資料型別 json是一種輕量級的資料交換結構,他使得人們很容易進行閱讀和編寫,同時方便了機器進行解析和生成。適用於進行資料交換場景,比如 前台與後台之間的資料互動。js...