Python 学习 —— 格式化文件JSON

版权声明:转载注明出处 https://blog.csdn.net/qq_19428987/article/details/87946369

格式化文件读取一般有XML和JSON,但是JSON使用上相对更加简洁,重点了解了一下JSON:

  • json.dumps(student):Python对象转JSON
  • json.loads(stu_json):json字符串转Python可读取对象
import json
student={"name":"Lidian","age":18,"Phone":18508211005}
print(type(student))
stu_json=json.dumps(student)
print(type(stu_json))
print("JSON对象:{0}".format(stu_json))
stu_dict=json.loads(stu_json)
print(type(stu_dict))
print(stu_dict)
输出结果:
<class 'dict'>
<class 'str'>
JSON对象:{"name": "Lidian", "age": 18, "Phone": 18508211005}
<class 'dict'>
{'name': 'Lidian', 'age': 18, 'Phone': 18508211005}
  • json.dump(student,f):写入json
  • d=json.load(f):读取json
import json
student={"name":"Lidian","age":18,"Phone":18508211005}
with open("t.json","w") as f:
    json.dump(student,f)
with open("t.json","r") as f:
    d=json.load(f)
    print(d)
 输出结果:
 {'name': 'Lidian', 'age': 18, 'Phone': 18508211005}

JSON详细教程

猜你喜欢

转载自blog.csdn.net/qq_19428987/article/details/87946369