python-- json 序列化


前戏

序列化:得到一个字符串的过程就叫序列化

字典 / 列表 / 数字 /对象 -经过序列化 --->字符串

字符串-反序列化 ---> 字典 / 列表 / 数字 /对象

为什么要序列化

  • 要把内容写入文件 序列化
  • 网络传输数据 序列化

json

转为字符串 dumps

import json

dic = {"aaa": "bbb", "ccc": "ddd"}
str_dic = json.dumps(dic)
print(dic, type(dic))
print(str_dic, type(str_dic))

输出结果:
{'aaa': 'bbb', 'ccc': 'ddd'} 
{"aaa": "bbb", "ccc": "ddd"} 

反序列化 loads

import json

# 只提供四个方法
dic = '{"aaa":"bbb","ccc":"ddd"}'
str_dic = json.loads(dic)
print(dic, type(dic))
print(str_dic, type(str_dic))

输出结果:
{"aaa":"bbb","ccc":"ddd"} 
{'aaa': 'bbb', 'ccc': 'ddd'} 

如果要将字典写入文件,要先序列化后再写入

  import json
dic = {"aaa": "bbb", "ccc": "ddd"}
str_dic = json.dumps(dic)  # 将字典转为字符串
with open('json_dump', 'w') as f:
    f.write(str_dic)

也可以使用 dump 写入,不需要转为字符串

import json

dic = {'aaa': 'bbb', 'ccc': 'ddd'}
with open('json_dump2', 'w') as f:
    json.dump(dic, f)  # 第一个参数为要写入的内容,第二个参    数为文件句柄

从文件里读取出来就是反序列化后的,用load,但是文件里的字符串必须是英文状态下的双引号,如果是单引号则会报错

import json

with open('json_dump2', 'r', encoding='utf-8') as f:
    ret = json.load(f)
    print(ret)

json模块其他用法

json 格式的限制

# json格式的限制1,json格式的key必须是字符串数据类型
# json格式中的字符串只能是""
# set不能被dump/dumps

如果是数字为key,那么dumps之后会强行转成字符串数据类型

import json

dic = {1:2,3:4}
str_dic = json.dumps(dic)
print(str_dic)

new_dic = json.loads(str_dic)
print(new_dic)

输出结果:
{"1": 2, "3": 4}
{'1': 2, '3': 4}

json支持元组做value,对元组做value的字典,会把元组强制转换成列表

import json

dic = {'abc': (1, 2, 3)}
str_dic = json.dumps(dic)
print(str_dic)
new_dic = json.loads(str_dic)
print(new_dic)
输出结果:
{"abc": [1, 2, 3]}
{'abc': [1, 2, 3]}

json不支持元组做key

import json

dic = {(1, 2, 3): 'abc'}
str_dic = json.dumps(dic)  # 报错

对列表的dump

import json

lst = ['aaa', 123, 'bbb', 12.456]
with open('json_demo', 'w') as f:
    json.dump(lst, f)
with open('json_demo') as f:
    ret = json.load(f)
    print(ret)
输出结果:
['aaa', 123, 'bbb', 12.456]

可以多次dump数据到文件里,但是不能load出来了

import json

dic = {'abc': (1, 2, 3)}
lst = ['aaa', 123, 'bbb', 12.456]
with open('json_demo', 'w') as f:
    json.dump(lst, f)
    json.dump(dic, f)

with open('json_demo') as f:
    ret = json.load(f)  # 会报错
    print(ret)

想dump多个数据进入文件,用dumps

import json

dic = {'abc': (1, 2, 3)}
lst = ['aaa', 123, 'bbb', 12.456]
with open('json_demo', 'w') as f:
    str_lst = json.dumps(lst)
    str_dic = json.dumps(dic)
    f.write(str_lst + '\n')
    f.write(str_dic + '\n')

with open('json_demo') as f:
    for line in f:
        ret = json.loads(line)
        print(ret)
输出结果:
['aaa', 123, 'bbb', 12.456]
{'abc': [1, 2, 3]}

json的参数

import json

data = {'username': ['李华', '二愣子'], 'sex': 'male', 'age': 16}

参数1:  sort_keys=True,key按照ascii排序


参数2:  indent缩进几个字符


参数3:  ensure_ascii不以ascii编码   (若中文乱码则加上这个)


json_dic2 = json.dumps(data, sort_keys=True, indent=4, separators=(',', ':'), ensure_ascii=False)
print(json_dic2)
输出结果:
{
    "age":16,
    "sex":"male",
    "username":[
        "李华",
        "二愣子"
    ]
}