python3.x 基础四:json与pickple

  • 每次打开一个文件,只dump1次
  • json.dump(dump的内容,文件句柄)
  • json.load(文件句柄)
  • json可以处理列表/字典/字符串等简单数据类型,但是不能处理复杂的数据类型,如函数的内存地址
  • 不同语言间都可以用json文件
import json
dict1={'name':'alex','age':22,'salary':1000}
print('dict is %s\ndumping dict to file...' % (dict1))
fd = open('fd.txt','w',encoding='utf-8')
# with open('fd.txt','w',encoding='utf-8') as fd:
#     json.dump(dict1,fd)
dict2={'name':'oldboy','age':32,'salary':2000}
# with open('fd.txt','w',encoding='utf-8') as fd:
#     json.dump(dict2,fd)
json.dump(dict1,fd)
fd.close()
# json.dump(dict2,fd)
fd = open('fd.txt','r',encoding='utf-8')
print('load content from file...')
print(json.load(fd))
fd.close()
output:
dict is {'age': 22, 'salary': 1000, 'name': 'alex'}
dumping dict to file...
load content from file...
{'age': 22, 'salary': 1000, 'name': 'alex'}
dumping dict to file...
import json
dict1={}
def func():
    print('in the func')
dict1['name']=func
fd = open('fdw.txt','w',encoding='utf-8')
print('dumping dict to file...' % (dict1))
json.dumps(dict1,fd)
fd.close()
error:
TypeError: <function func at 0x7f0828c68488> is not JSON serializable
  • pickle能处理python所有的数据类型
import pickle
dict1={}
def func():
    print('in the func')
dict1['name']=func
fd = open('fdw.txt','wb')
print('dumping dict to file... %s' % (dict1))
pickle.dump(dict1,fd)
fd.close()
fd = open('fdw.txt','rb')
print(pickle.load(fd))
fd.close()
output:
dumping dict to file... {'name': <function func at 0x7fa1904d4488>}
{'name': <function func at 0x7fa1904d4488>}

 

dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Serialize ``obj`` to a JSON formatted ``str``.

  • 将一个对象转换成json格式的字符串

loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.

  • 将一个json格式的对象反序列成python对象
import json
l1 = ["alex", 123, "eric"]
l2 = ["alex", 123, 'eric']
s1 = """ ["alex", 123, "eric"] """
s2 = """ ["alex", 123, 'eric'] """
print(json.dumps(l1),type(json.dumps(l1))) # list to str
print(json.dumps(l2),type(json.dumps(l2))) # list to str
print(json.dumps(s1),type(json.dumps(s1))) # still str
print(json.dumps(s2),type(json.dumps(s2))) # still str

# 四个正确
# print(json.loads(l1)) # json格式需要字符串,这是列表
# print(json.loads(l2))  # 同上
print(json.loads(s1),type(json.loads(s1))) # str to list,json格式需要双引号
# print(json.loads(s2)) # 格式错误,有单引号

dict1={}
dict1["name"]="xxx"
print(json.dumps(dict1),type(json.dumps(dict1)))
# str1='''dict1["name"]="xxx"'''
# print(json.loads(str))

l = ['iplaypython', [1, 2, 3], {'name':'xiaoming'}]
encoded_json = json.dumps(l)
print(encoded_json,type(encoded_json))
decode_json = json.loads(encoded_json)
print(decode_json,type(decode_json))

输出

["alex", 123, "eric"] <class 'str'>
["alex", 123, "eric"] <class 'str'>
" [\"alex\", 123, \"eric\"] " <class 'str'>
" [\"alex\", 123, 'eric'] " <class 'str'>
['alex', 123, 'eric'] <class 'list'>
{"name": "xxx"} <class 'str'>
["iplaypython", [1, 2, 3], {"name": "xiaoming"}] <class 'str'>
['iplaypython', [1, 2, 3], {'name': 'xiaoming'}] <class 'list'>

 

posted @ 2017-11-25 15:11  Jenvid  阅读(574)  评论(0编辑  收藏  举报