json模块

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模块

上一篇:Webpack实战(入门、进阶与调优)


下一篇:java微信公众平台开发事件推送