python基础_json模块

1.json模块可以序列化的数据、

所有编程语言都能够识别的数据格式叫做json,是字符串
如下类型可以转换成json字符串: int float bool str list tuple dict None

ensure_ascii=False 显示中文
sort_keys = True 对字典的键进行排序

 

2.实际案例

# ### 1.json用法
import json
# (1)dumps 和 loads 是一对, 序列化成字符串.
# dumps序列化成字符串
dic = {"name":"张三","age":18,"classroom":"python7","family":["老爸","老妈","妹妹"]}
res = json.dumps(dic,ensure_ascii=False,sort_keys=True)
print(res,type(res))

# loads反序列化成原来的数据类型
dic = json.loads(res)
print(dic,type(dic))

# (2) dump 和 load 是一对,针对于文件操作
dic = {"name":"张三","age":18,"classroom":"python7","family":["老爸","老妈","妹妹"]}
# dump(要转化的数据,文件对象,关键字实参...)
with open("ceshi1.json",mode="w",encoding="utf-8") as fp:
    json.dump(dic,fp,ensure_ascii=False)

# load(文件对象)
with open("ceshi1.json",mode="r",encoding="utf-8") as fp:
    dic = json.load(fp)
print(dic,type(dic))

3.json数据连续dump和load操作

# (1)json
"""
可以连续dump , 不可以连续load
load 特征是一次性把所有的内容都取出来变成一个完整的字典;
所以如果是多个字典不能够转化; 

# 解决方式:
loads 可以 配合遍历文件对象,一行一行读取内容,在通过loads来转换成原来的数据类型
"""
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
with open("ceshi2.json",mode="w",encoding="utf-8") as fp:
    json.dump(dic1,fp)
    fp.write("\n")
    json.dump(dic2,fp)
    fp.write("\n")
    
# 文件对象是迭代器,可以遍历;
from collections import Iterator,Iterable
res = isinstance(fp,Iterator)
print(res)

# 用loads 来解决load存在的弊端;
with open("ceshi2.json",mode="r",encoding="utf-8") as fp:
    for i in fp:
        # print(i,type(i))
        dic = json.loads(i)
        print(dic,type(dic))

4.pickle连续dump和load操作

# (2)pickle
print("<===>")
import pickle
"""
可以连续dump ,也可以连续load
"""
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
with open("ceshi3.pkl",mode="wb") as fp:
    pickle.dump(dic1,fp)
    pickle.dump(dic2,fp)
    
# 方法一
with open("ceshi3.pkl",mode="rb") as fp:
    dic1 = pickle.load(fp)
    dic2 = pickle.load(fp)
    
print(dic1,type(dic1))
print(dic2,type(dic2))

# 方法二
try:
    with open("ceshi3.pkl",mode="rb") as fp:
        while True:
            dic = pickle.load(fp)
            print(dic)
except:
    pass

 

posted @ 2020-06-21 19:56  jalen-tian  阅读(111)  评论(0编辑  收藏  举报