json与字典的转换

 1. json序列化(字典转成字符串)方法:

          dumps:无文件操作            dump:序列化+写入文件

  2. json反序列化(字符串转成字典)方法:

          loads:无文件操作              load: 读文件+反序列化

例子:dumps(字典转换成字符串,再写入文件)

d = {'s':'you','d':'are'}

import json
#字典转换成字符串再写入文件
with open('3.json', 'w', encoding='utf-8') as f:
    s = json.dumps(d, ensure_ascii=False, indent=4)#把字典转成json,字符串,ensure_ascii=False表示写入后中文直接写成中文,indent = 4表示设置缩进
    f.write(s)

dumps(字典转换成字符串,同时写入文件)

d = {'s':'you','d':'are'}

import json
#字典转换成字符串再写入文件
with open('3.json', 'w', encoding='utf-8') as f:
    # s = json.dumps(d, ensure_ascii=False, indent=4)#把字典转成json,字符串,ensure_ascii=False表示写入后中文直接写成中文,indent = 4表示设置缩进
    # f.write(s)
    json.dump(d, f, indent=4, ensure_ascii=False)#dumps操作字符串,dump操作文件
loads(读取文件中字典格式字符串,再转换成字典)
import json
#文件中读取字典格式字符串,再转换成字典
with open('3.txt', encoding='utf-8') as fr:
    result = fr.read()
    print(type(result))
    dic = json.loads(result)
    print(dic, type(dic))

load(直接从文件中读取字典格式字符串,并转换成字典)

import json
#文件中读取字典格式字符串,再转换成字典
with open('3.txt', encoding='utf-8') as fr:
    # result = fr.read()
    # print(type(result))
    # dic = json.loads(result)
    # print(dic, type(dic))
    result = json.load(fr)#load 字典格式字符串直接转换成字典
    print(type(result))

猜你喜欢

转载自www.cnblogs.com/rj-tsl/p/11024256.html
今日推荐