码迷,mamicode.com
首页 > Web开发 > 详细

json模块

时间:2021-05-24 05:07:40      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:strong   xxxxx   模块   pytho   odi   json模块   col   result   com   

import json
import pprint

  {"code":0,"msg":"操作成功","token":"xxxxx"}
  json是一个字符串


  python的数据类型转成json
  d = {"code":0,"msg":"操作成功","token":"xxxxx"}
  pprint.pprint(d)
  json_str = json.dumps(d,ensure_ascii=False)    字典转换成json字符串
  pprint.pprint(json_str)  unicode

  json转成python的数据类型
  json_str = ‘{"code": 0, "msg": "操作成功", "token": "xxxxx"}‘
  dic = json.loads(json_str)    json转换成字典
  pprint.pprint(dic)


  with open("student.txt",encoding="utf-8") as f:
       dic = json.loads(f.read())

  d = {"code":0,"msg":"操作成功",
       "token":"xxxxx","addr":"xxxx","sdgsdg":"xxx",
       "sdfsdf":"sdgsdg","s11":"111"}

   with open("student2.json",‘w‘,encoding="utf-8") as f:
       json_str = json.dumps(d,ensure_ascii=False,indent=4)
       f.write(json_str)

   with open("student2.json",encoding="utf-8") as f:
        result = json.load(f)

  with open("student2.json",‘w‘,encoding="utf-8") as f:
      json.dump(d,f,ensure_ascii=False,indent=4)

  loads  dumps    不操作文件

  load  dump    只能操作文件

bejson.com 可以校验json串合法性

json模块

标签:strong   xxxxx   模块   pytho   odi   json模块   col   result   com   

原文地址:https://www.cnblogs.com/my-own-goddess/p/14753788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!