python json 函数的使用,dumps;loads;dump;load

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/teachskyLY/article/details/84197715

python json 函数的使用dumps;loads;dump;load

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

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

import json
#python 字典型转换为JSON对象

data = {
	"type": "create",
	"username": "007",
	"password": "032475c0fa1cc0b91a5",
	"createTime": "2018-11-17 10:20:10.771",
	"name":"王根",
	"status": "1",
	"text": "zjesjoge收到货的时刻"
}

json_str = json.dumps(data)
#避免出现输出的json数据出现Unicode码  ensure_ascii=False
#indent=数字 ,用于缩进
json_best = json.dumps(data, ensure_ascii=False,indent=2)

print("原始数据: ",repr(data))
print("JSON 对象: ",json_str)
print("JSON2 对象: ",json_best)


data2 =json.loads(json_str)
print("data2['name']:",data2['name'])
print("data2['text']:",data2['text'])

输出结果


原始数据:  
{'type': 'create', 'username': '007', 'password': '48875c0fa1cc0113b91a5', 'createTime': '2017-07-17 14:00:10.771', 'name': '王根', 'status': '1', 'text': 'zjesjoge收到货的时刻'}
JSON 对象:  
{"type": "create", "username": "007", "password": "48875c0fa1cc0113b91a5", "createTime": "2017-07-17 14:00:10.771", "name": "\u738b\u6839", "status": "1", "text": "zjesjoge\u6536\u5230\u8d27\u7684\u65f6\u523b"}
JSON2 对象:  {
  "type": "create",
  "username": "007",
  "password": "48875c0fa1cc0113b91a5",
  "createTime": "2017-07-17 14:00:10.771",
  "name": "王根",
  "status": "1",
  "text": "zjesjoge收到货的时刻"
}
data2['name']: 王根
data2['text']: zjesjoge收到货的时刻
[Finished in 0.1s]

如果你要处理的是文件而不是字符串,

你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据

#内置函数open(file, mode='r')打开文件,关闭文件close()

#写入 JSON 数据
with open('data.json', 'w') as f:
    json.dump(data,f,ensure_ascii=False)

 
#读取数据

with open('data.json', 'r') as f:
    s2 = json.load(f)

 print (s2)	

#练习
import json

name = input("请输入你的名字")

phone = input("请输入你的电话号码")

data = json.dumps({"name":name,
				 "phone":phone}, ensure_ascii = False, indent=4)

print (data)

参考:https://www.runoob.com/python3/python3-json.html

猜你喜欢

转载自blog.csdn.net/teachskyLY/article/details/84197715
今日推荐