json模块

2021-05-29 02:03

阅读:415

标签: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


评论


亲,登录后才可以留言!