1、Json简介:
Json,全名 JavaScript Object Notation,是一种轻量级的数据交换格式。Json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式。现在也常用于http请求中,所以对json的各种学习,是自然而然的事情。
2、json类型和python数据的转换
import json
# 例子1
a = dict(name = 'andyfeng', age =20, message = 'hello')
print(a)
print(type(a))
b = json.dumps(a)
print(b)
print(type(b))
结果如下:
{'message': 'hello', 'age': 20, 'name': 'andyfeng'}
{"message": "hello", "age": 20, "name": "andyfeng"}
可以通过www.json.cn对json转换内容进行解析
{"message": "hello", "age": 20, "name": "andyfeng"}
解析后
{
"message":"hello",
"age":20,
"name":"andyfeng"}
3、json.loads()将json字符串解码成python对象。
在工作中,很多情况是别人给你提供的接口就是json字符串形式的。比如:你在数据库中查到的数据,返回结果是一个json的字符串的形式,这你就需要自己把这些json字符串转换成json对象。
import json
# 例子1
a = dict(name = 'andyfeng', age = 20, message = 'hello')
print(a)
print(type(a))
b = json.dumps(a)
print(b)
print(type(b))
# 例子2
print('@@@@@@@@@@@@@@')#标记用
c = json.loads(b)
print(type(c))
print(c)
结果如下:
{'message': 'hello', 'age': 20, 'name': 'andyfeng'}
{"message": "hello", "age": 20, "name": "andyfeng"}
@@@@@@@@@@@@@@
{u'message': u'hello', u'age': 20, u'name': u'andyfeng'}
说明:
通过json.loads方法把json字符串转换成python的数据字典。
4、文件和json之间的转换
#文件相关
# load肯定是从文件中逃出来json数据,load肯定是把文件转换成json数据
#dump 就是把json数据写入到文件中
# 把json写入文件中 dump
jsondata = '{"a":1, "b":2, "c":3, "d":4, "e":5}'#外面可以用单引号‘’或三个单引号‘‘‘ ’’’
with open('a.txt', 'w')as f:
json.dump(jsondata, f)
结果截图:
说明:
json.dump()可以把json数据直接写入到文件中。
5、json.load()
#文件相关
# load肯定是从文件中逃出来json数据,load肯定是把文件转换成json数据
#dump 就是把json数据写入到文件中
# 把json写入文件中 dump
jsondata = '{"a":1, "b":2, "c":3, "d":4, "e":5}'#外面可以用单引号‘’或三个单引号‘‘‘ ’’’
with open('a.txt', 'w')as f:
json.dump(jsondata, f)
with open('a.txt', 'r') as fr:
m = json.load(fr)
print(m)
print(type(m))
结果:
{"a":1, "b":2, "c":3, "d":4, "e":5}
Process finished with exit code 0
说明:
json.load()把文件内容转换成unicode数据类型返回