四、JSON总结
1.什么是JSON
- JSON指的是JavaScript对象表示法(JavaScript Object Notation)
- JSON是轻量级的文本数据交换格式
- JSON独立于语言
- JSON具有自我描述性,更易理解
2.什么是序列化
-
把变量从内存中变成可存储或传输的过程称为序列化
-
序列化在Python中叫pickling
在其他语言中也被称之为serialization、marshalling、flattening
-
序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上
-
反过来,把变量内容从序列化的对象重新读到内存里称为反序列化,即unpickling
3.JSON序列化的优势
- 在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML
- JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输
- JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中获取
- 很多HTTP接口都采用JSON格式传输数据
4.解析JSON
- 创建下面包含JSON数据的字符串
json_string = '{"first_name": "Guido", "last_name":"Rossum"}'
- 可以被这样解析
import json
parsed_json = json.loads(json_string)
- 可以把下面这个对象转为JSON
import json
d = {
'first_name': 'Guido',
'second_name': 'Rossum',
'titles': ['BDFL', 'Developer'],
}
print(json.dumps(d))
# '{"first_name": "Guido", "last_name": "Rossum", "titles": ["BDFL",
"Developer"]}'
五、json模块实践
1.json模块说明
- Python是原生态支持json
- 可以使用json模块处理json数据
- json模块支持的2个最基本的使用方法
- dumps:把字典转成json字符串(序列化)
- loads:把json字符串转成字典(反序列化)
2.json模块常见使用
- 使用dumps方法将字典转成json字符串,并保存到文件中
#coding:utf-8
import json
import codecs
test_dict = {'a':1, 'b':2}
# 把字典转成json字符串
json_text = json.dumps(test_dict)
# 把json字符串保存到文件中
# 因为可能json有unicode编码,最好用codecs保存utf-8文件
with codecs.open('1.json', 'w', 'utf-8') as f:
f.write(json_text)
可以看到a和b都被双引号引用
但是字母看不出明显的区别,在这里把字母改成汉字再来看看结果
import json
import codecs
test_dict = {'一':1, '二':2}
# 把字典转成json字符串
json_text = json.dumps(test_dict)
with codecs.open('2.json', 'w', 'utf-8') as f:
f.write(json_text)
print(json_text)
- 使用dump方法将字典转成json字符串,并保存到文件中
#coding:utf-8
import json
import codecs
test_dict = {'a':1, 'b':2}
# 把字典转成json字符串并写入到文件
with codecs.open('1.json', 'w', 'utf-8') as f:
json.dump(test_dict, f)
- 使用loads方法从json文件中读取到字典中
#coding:utf-8
import json
import codecs
# 从文件中读取内容
with codecs.open('1.json', 'r', 'utf-8') as f:
json_text = f.read()
# 把字符串转成字典
json_dict = json.loads(json_text)
print(json_dict)
- 使用load方法从json文件中读取到字典中
#coding:utf-8
import json
import codecs
# 从文件中读取内容到字典
with codecs.open('1.json', 'r', 'utf-8') as f:
json_dict = json.load(f)
print(json_dict)
- 将json字符串转换成有序的字典
# coding:utf-8
from collections import OrderedDict
import json
json_text = '{ "b": 3, "a": 2, "c": 1}'
json_dict = json.loads(json_text)
print(u"转成普通字典")
for key, value in json_dict.items():
print("key:%s, value:%s" % (key, value))
json_dict1 = json.loads(json_text, object_pairs_hook=OrderedDict)
print(u"\n转成有序字典")
for key, value in json_dict1.items():
print("key:%s, value:%s" % (key, value))
OrderedDict 有序字典以及读取json串时如何保持原有顺序