python json pickle 模块

json

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。

JSON建构于两种结构:

“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
这些都是常见的数据结构。事实上大部分现代计算机语言都以某种形式支持它们。这使得一种数据格式在同样基于这些结构的编程语言之间交换成为可能。

在python中,json的数据格式与字典很像,json的引号为双引号,不存在元组,集合类型,如果在序列化时有元组,集合类型会被转成列表形式

+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str | string |
+-------------------+---------------+
| int, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+

json序列化操作

import json
dic = {'a':1,'b':'yyf','c':['1',2],'d':('x','y')}
jsn = json.dumps(dic)
print(jsn)
json.dump(dic,open('01.txt','w',encoding='utf-8'))

{"a": 1, "b": "yyf", "c": ["1", 2], "d": ["x", "y"]}

 

json反序列化操作

with open('01.txt','r',encoding='utf-8') as f:
    str1 = f.read()
    print(json.loads(str1))
dic = json.load(open('01.txt','r',encoding='utf-8'))
print(dic)

{'a': 1, 'b': 'yyf', 'c': ['1', 2], 'd': ['x', 'y']}

使用json.dumps()序列化时间对象

在JSONEncoder中的default方法

    def default(self, o):
        """Implement this method in a subclass such that it returns
        a serializable object for ``o``, or calls the base implementation
        (to raise a ``TypeError``).

        For example, to support arbitrary iterators, you could
        implement default like this::

            def default(self, o):
                try:
                    iterable = iter(o)
                except TypeError:
                    pass
                else:
                    return list(iterable)
                # Let the base class default method raise the TypeError
                return JSONEncoder.default(self, o)

        """
        raise TypeError(f'Object of type {o.__class__.__name__} '
                        f'is not JSON serializable')

以上代码可以看出如果json.dump不支持的数据类型则会报错

"""
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'date' is not JSON serializable
"""

因此我们要重写default方法

import json
from datetime import datetime,date
class MyJson(json.JSONEncoder):
    def default(self, o):
        if isinstance(o,datetime):
            return o.strftime('%Y-%m-%d %X')
        elif isinstance(o,date):
            return o.strftime('%Y-%m-%d')
        else:
            super().default(self,o)


res = {'c1':datetime.now(),'c2':date.today()}
print(json.dumps(res,cls=MyJson))

这样就可以实现json.dump支持时间对象类型了

 

pickle

pickle是python中的特有类型,用于python的数据类型间进行转换

支持python中的所有原生类型:布尔值,整数,浮点数,复数,字符串,字节,None

支持由任何原生类型组成的列表,元组,字典和集合

支持函数,类,类的实例

pickle序列化

import pickle
dic = {'a':'b'}
f = open('01.txt','wb')
pickle.dump(dic,f)
f.close()
res = pickle.dumps(dic)
print(res)

b'\x80\x03}q\x00X\x01\x00\x00\x00aq\x01X\x01\x00\x00\x00bq\x02s.'

 

pickle反序列化

with open('01.txt','rb') as f:
    str = f.read()
    lst = pickle.loads(str)
    res = pickle.load(f)
    print(res)
    print(lst)

{'a': 'b'}
{'a': 'b'}

 

posted @ 2019-04-18 15:12  yyfgrd  阅读(246)  评论(0编辑  收藏  举报