(五)5-1 json

json简介:全称JavaScript Object Notation是一种轻量级的数据交换格式。
json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式
1、json类型和python数据的转换

loads 单词意思:加载 把json格式转换成字符串
dumps 单词意思:颠倒 就是把其他对象或者格式,转换成json格式

a、json.dumps()将python对象编码转换为json字符串
import json
m = {'sucess':True,'message':'hello'}
json_str = json.dumps(m)
print(json_str)
print(type(json_str))
运行结果:
{"message": "hello", "sucess": true}
<type 'str'>
注:
Data是一个python数据字典,最后通过json.dumps函数把data转换成字符串的形式。

b、json.loads() 讲json字符串解码成python对象
import json
dic = dict(name="zhangsan",age=88,message="hello")
a = json.dumps(dic)
print(a)
print(type(a))
c = json.loads(a)
print(type(c))
print(c)
运行结果:
{"message": "hello", "age": 88, "name": "zhangsan"}
<type 'str'>
<type 'dict'>
{u'message': u'hello', u'age': 88, u'name': u'zhangsan'}
注:通过json.loads 将json字符串转为python字典

10.8.2 json(下)

2、文件和json之间的转换
load 从文件中导出json数据,load把文件转换成json数据
dump 把json数据写入到文件中
例:
#json.dump()可以把json数据直接写入到文件中。
import codecs
jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
# print(jsonData)
with codecs.open("json.txt","w") as fd:
json.dump(jsonData,fd)

#json.load() json.load()把文件内容转换成unicode数据类型返回
with codecs.open("json.txt","r") as fd :
m = json.load(fd)
print(m)
print(type(m))
运行结果:
{"a":1,"b":2,"c":3,"d":4,"e":5}
<type 'unicode'>

cat json.txt
"{"a":1,"b":2,"c":3,"d":4,"e":5}"

扩展:
json解析网址https://www.json.cn/

原文地址:https://www.cnblogs.com/pythonlx/p/7829134.html