首页 > Web开发 > 详细

json与字典的转换

时间:2019-06-14 17:23:39      阅读:133      评论:0      收藏:0      [点我收藏+]

 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))

 

json与字典的转换

原文:https://www.cnblogs.com/rj-tsl/p/11024256.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!