import json
json.dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True,cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False,**kw)
obj = [[1,2,3],123,123.123,'abc',{'key1':(1,2,3),'key2':(4,5,6)}]
encodedjson = json.dumps(obj)
print 'the original list:\n',obj
print 'length of obj is:',len(repr(obj))
print 'repr(obj),replace whiteblank with *:\n', repr(obj).replace(' ','*')
print 'json encoded,replace whiteblank with *:\n',encodedjson.replace(' ','*')
the original list:
[[1, 2, 3], 123, 123.123, 'abc', {'key2': (4, 5, 6), 'key1': (1, 2, 3)}]
length of obj is: 72
repr(obj),replace whiteblank with *:
[[1,*2,*3],*123,*123.123,*'abc',*{'key2':*(4,*5,*6),*'key1':*(1,*2,*3)}]
json encoded,replace whiteblank with *:
[[1,*2,*3],*123,*123.123,*"abc",*{"key2":*[4,*5,*6],*"key1":*[1,*2,*3]}]
<type 'list'>
decodejson = json.loads(encodedjson) print 'the type of decodeed obj from json:', type(decodejson) print 'the obj is:\n',decodejson print 'length of decoded obj is:',len(repr(decodejson))
the type of decodeed obj from json: <type 'list'>
the obj is:
[[1, 2, 3], 123, 123.123, u'abc', {u'key2': [4, 5, 6], u'key1': [1, 2, 3]}]
length of decoded obj is: 75 #比原obj多出了3个unicode编码标示‘u'
data1 = {'b':789,'c':456,'a':123}
data2 = {'a':123,'b':789,'c':456}
d1 = json.dumps(data1,sort_keys=True)
d2 = json.dumps(data2)
d3 = json.dumps(data2,sort_keys=True)
print 'sorted data1(d1):',d1
print 'unsorted data2(d2):',d2
print 'sorted data2(d3):',d3
print 'd1==d2?:',d1==d2
print 'd1==d3?:',d1==d3
sorted data1(d1): {"a": 123, "b": 789, "c": 456}
unsorted data2(d2): {"a": 123, "c": 456, "b": 789}
sorted data2(d3): {"a": 123, "b": 789, "c": 456}
d1==d2?: False
d1==d3?: True
data = {'b':789,'c':456,'a':123}
d1 = json.dumps(data,sort_keys=True,indent=4)
print 'data len is:',len(repr(data))
print '4 indented data:\n',d1
d2 = json.loads(d1)
print 'decoded DATA:', repr(d2)
print 'len of decoded DATA:',len(repr(d2))
data len is: 30
4 indented data:
{
"a": 123,
"b": 789,
"c": 456
}
decoded DATA: {u'a': 123, u'c': 456, u'b': 789}
len of decoded DATA: 33
data = {'b':789,'c':456,'a':123}
print 'DATA:', repr(data)
print 'repr(data) :', len(repr(data))
print 'dumps(data) :', len(json.dumps(data))
print 'dumps(data, indent=2) :', len(json.dumps(data, indent=4))
print 'dumps(data, separators):', len(json.dumps(data, separators=(',',':')))
DATA: {'a': 123, 'c': 456, 'b': 789}
repr(data) : 30
dumps(data) : 30
dumps(data, indent=2) : 46
dumps(data, separators): 25
data = {'b':789,'c':456,(1,2):123}
print'original data:',repr(data)
print 'json encoded',json.dumps(data,skipkeys=True)
original data: {(1, 2): 123, 'c': 456, 'b': 789}
json encoded {"c": 456, "b": 789}
#handling private data type
#define class
class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
def __repr__(self):
return 'Person Object name : %s , age : %d' % (self.name,self.age)
#define transfer functions
def object2dict(obj):
#convert object to a dict
d = {'__class__':obj.__class__.__name__, '__module__':obj.__module__}
d.update(obj.__dict__)
return d
def dict2object(d):
#convert dict to object
if'__class__' in d:
class_name = d.pop('__class__')
module_name = d.pop('__module__')
module = __import__(module_name)
print 'the module is:', module
class_ = getattr(module,class_name)
args = dict((key.encode('ascii'), value) for key, value in d.items()) #get args
print 'the atrribute:', repr(args)
inst = class_(**args) #create new instance
else:
inst = d
return inst
#recreate the default method
class LocalEncoder(json.JSONEncoder):
def default(self,obj):
#convert object to a dict
d = {'__class__':obj.__class__.__name__, '__module__':obj.__module__}
d.update(obj.__dict__)
return d
class LocalDecoder(json.JSONDecoder):
def __init__(self):
json.JSONDecoder.__init__(self,object_hook = self.dict2object)
def dict2object(self, d):
#convert dict to object
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()) #get args
inst = class_(**args) #create new instance
else:
inst = d
return inst
#test function
if __name__ == '__main__':
p = Person('Aidan',22)
print p
#json.dumps(p)#error will be throwed
d = object2dict(p)
print 'method-json encode:', d
o = dict2object(d)
print 'the decoded obj type: %s, obj:%s' % (type(o),repr(o))
dump = json.dumps(p,default=object2dict)
print 'dumps(default = object2dict):',dump
load = json.loads(dump,object_hook = dict2object)
print 'loads(object_hook = dict2object):',load
d = LocalEncoder().encode(p)
o = LocalDecoder().decode(d)
print 'recereated encode method: ',d
print 'recereated decode method: ',type(o),o
Person Object name : Aidan , age : 22
method-json encode: {'age': 22, '__module__': '__main__', '__class__': 'Person', 'name': 'Aidan'}
the module is: <module '__main__' from 'D:/Project/Python/study_json'>
the atrribute: {'age': 22, 'name': 'Aidan'}
the decoded obj type: <class '__main__.Person'>, obj:Person Object name : Aidan , age : 22
dumps(default = object2dict): {"age": 22, "__module__": "__main__", "__class__": "Person", "name": "Aidan"}
the module is: <module '__main__' from 'D:/Project/Python/study_json'>
the atrribute: {'age': 22, 'name': u'Aidan'}
loads(object_hook = dict2object): Person Object name : Aidan , age : 22
recereated encode method: {"age": 22, "__module__": "__main__", "__class__": "Person", "name": "Aidan"}
recereated decode method: <class '__main__.Person'> Person Object name : Aidan , age : 22
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有