Python常用模块之json

本章节我们将为大家介绍如何使用 Python 语言来编码和解码 JSON 对象。

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。

SON 函数

使用 JSON 函数需要导入 json 库:import json

函数描述
json.dumps  将 Python 对象编码成 JSON 字符串
json.loads  将已编码的 JSON 字符串解码为 Python 对象

json.dumps

import json

user={"name":"yinxin"}
user=json.dumps(user)

print(type(user))

<class 'str'

 

#使用文件进行json.dumps

#1

with open("user.json","w",encoding="utf-8"as w:

  w.write(json.dumps(user))

#2

json.dump(user,open("user1.json","w",encoding="utf-8"

 

json.loads

dict=json.load(open("user1.json","r",encoding="utf-8"))

print(dict)

with open("user1.json","r",encoding="utf-8"as f:

print(json.loads(f.read()))

 

原文地址:https://www.cnblogs.com/yinxin/p/8309656.html