• json & pickle 模块


    json模块

    Json模块提供了四个功能:dumps、dump、loads、load

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import json
    dic = {'k1':1,'k2':2,'k3':3}
    str_dic = json.dumps(dic)  ##序列化:将一个字典转换成一个字符串
    print(type(str_dic),str_dic)  #<class 'str'> {"k1": 1, "k2": 2, "k3": 3}
    #注意,json转换完的字符串类型的字典中的字符串是由""表示的
    dic2 = json.loads(str_dic)#反序列化:将一个字符串格式的字典转换成一个字典
    print(dic2)#{'k1': 1, 'k2': 2, 'k3': 3}
    #注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示
    list_dic = [1,['k1:1'],'a','b','c',[1,2,3]] #也可以处理嵌套的数据类型 
    str_dic = json.dumps(list_dic)
    print(type(list_dic),list_dic)  #<class 'list'> [1, ['k1:1'], 'a', 'b', 'c', [1, 2, 3]]
    str_dic2 = json.loads(str_dic)
    print(type(str_dic2),str_dic2) #<class 'list'> [1, ['k1:1'], 'a', 'b', 'c', [1, 2, 3]]
    loads和dumps
    import json
    f = open('json_file','w')
    dic = {'k1':'v1','k2':'v2','k3':'v3'}
    json.dump(dic,f)  #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
    f.close()
    
    f = open('json_file')
    dic2 = json.load(f)  #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
    f.close()
    print(type(dic2),dic2)
    
    load和dump
    load和dump
    import json
    f = open('file','w')
    json.dump({'国籍':'中国'},f)
    ret = json.dumps({'国籍':'中国'})
    f.write(ret+'
    ')
    json.dump({'国籍':'美国'},f,ensure_ascii=False)
    ret = json.dumps({'国籍':'美国'},ensure_ascii=False)
    f.write(ret+'
    ')
    f.close()
    ensure_ascii关键字参数
    Serialize obj to a JSON formatted str.(字符串表示的json对象) 
    Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key 
    ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。) 
    If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). 
    If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity). 
    indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json 
    separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。 
    default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. 
    sort_keys:将数据根据keys的值进行排序。 
    To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
    其他参数说明
    import json
    data = {'username':['李华','二愣子'],'sex':'male','age':16}
    json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False)
    print(json_dic2)
    json的格式化输出

    用于序列化的两个模块

    • json,用于字符串 和 python数据类型间进行转换
    • pickle,用于python特有的类型 和 python的数据类型间进行转换 

    pickle模块提供了四个功能:dumps、dump(序列化,存)、loads(反序列化,读)、load  (不仅可以序列化字典,列表...可以把python中任意的数据类型序列化

    import pickle
    dic = {'k1':'v1','k2':'v2','k3':'v3'}
    str_dic = pickle.dumps(dic)
    print(str_dic)  #一串二进制内容
    
    dic2 = pickle.loads(str_dic)
    print(dic2)    #字典
    
    import time
    struct_time  = time.localtime(1000000000)
    print(struct_time)
    f = open('pickle_file','wb')
    pickle.dump(struct_time,f)
    f.close()
    
    f = open('pickle_file','rb')
    struct_time2 = pickle.load(f)
    print(struct_time2.tm_year)
    pickle

    这时候机智的你又要说了,既然pickle如此强大,为什么还要学json呢?
    这里我们要说明一下,json是一种所有的语言都可以识别的数据结构。
    如果我们将一个字典或者序列化成了一个json存在文件里,那么java代码或者js代码也可以拿来用。
    但是如果我们用pickle进行序列化,其他语言就不能读懂这是什么了~
    所以,如果你序列化的内容是列表或者字典,我们非常推荐你使用json模块
    但如果出于某种原因你不得不序列化其他的数据类型,而未来你还会用python对这个数据进行反序列化的话,那么就可以使用pickle

  • 相关阅读:
    【转】MyEclipse项目的字符编码设置
    【转】VS2008中 ATL CLR MFC Win32 区别
    【转】字符数组与字符指针
    【转】How to: Convert Between Various String Types
    【转】ATL基础BSTR CComBSTR SysAllocString
    【转】PHP ini_set ini_get 可操作配置参数列表
    【转】字符、字符数组、char、string的区别分析
    【转】PHP 计算页面执行时间
    【转】Java 如何判断String为空?
    【转】Converting char array to BSTR
  • 原文地址:https://www.cnblogs.com/zhaojingyu/p/9038369.html
Copyright © 2020-2023  润新知