Python常用模块 -- json模块常用用法

对Python数据类型进行序列化与反序列化

dic = {'name': 'sun', 'age': 19, 'gender': 1}
str_dic = json.dumps(dic)  # 序列化:将一个字典转换成一个字符串
print(str_dic, type(str_dic))

dic2 = json.loads(str_dic)  # 反序列化:将一个json字符串转换成一个字典
print(dic2, type(dic2))

# 还可以处理嵌套的数据类型
list_dic = [1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}]
str_dic = json.dumps(list_dic)
print(str_dic, type(str_dic))
list_dic2 = json.loads(str_dic)
print(list_dic2, type(list_dic2))

对文件句柄进行序列化与反序列化

# 对文件句柄进行序列化与反序列化
with open('json.txt', 'w') as f:
    json.dump(dic, f)

with open('json.txt') as f:
    dic_content = json.load(f)
    print('dic_content', dic_content)

# 注意。dump dumps 中文时,要将 ensure_ascii=False
with open('json1.txt', 'w') as f:
    json.dump({'国家': '中国', 'other': 'nothing'}, f, ensure_ascii=False)

with open('json2.txt', 'w') as f:
    json_content = json.dumps({'年龄': 18, '性别': '男'}, ensure_ascii=False)
    f.write(json_content)

猜你喜欢

转载自www.cnblogs.com/sunch/p/12402634.html