一、什么是JSON?
全称:JavaScript Object Notation, 即JavaScripe对象标记
本质:JSON是一种轻量级的数据交换格式,它是我们为了便于跨语言交换数据而定制的一种
数据格式
表现形式:字符串,符合JSON格式的字符串叫做JSON字符串
二、JSON的优势
- 易于阅读
- 易于解析
- 网络传输效率高
- 跨语言交换数据
三、在python中使用JSON(反序列化)
注意:可以在任何一种语言中找到一种与JSON对应的数据结构
1、JSON对象——>Python字典(dict)
例:
import json
json_str = '{"name":"qiyue","age":18}'
student = json.loads(json_str)
print(type(student))
print(student)
print(student["name"])
print(student["age"])
输出结果:
<class 'dict'>
{'name': 'qiyue', 'age': 18}
qiyue
18
我们发现,JSON对象的格式与Python中的字典很像,故Python中的字典与JSON对象对应
2、JSON数组(array)—>Python列表(list)
例:
json_str = '[{"name":"qiyue","age":18, "flag":false}, {"name":"qiyue","age":18}]'
student = json.loads(json_str)
print(type(student))
print(student)
输出结果:
<class 'list'>
[{'name': 'qiyue', 'age': 18, 'flag': False}, {'name': 'qiyue', 'age': 18}]
我们看到,JSON中的array对应于python中的列表,细心的同学会发现,JSON中的否为小写的
false,解析后会编程python中首字母大写的False
3、总的:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number | int |
number | float |
true | True |
false | False |
null | None |
4、序列化(Python—>JSON)
例:
student = [
{"name":"qiyue","age":18, "flag":False},
{"name":"qiyue","age":18}
]
json_str = json.dumps(student)
print(json_str)
输出结果:
[{"name": "qiyue", "age": 18, "flag": false}, {"name": "qiyue", "age": 18}]
我们看到false变为了小写,故转化为了JSON,即成功地序列化了
三、JSON对象、JSON的区别
1、在python角度看其实并没有JSON对象的
2、JSON是一种格式,它是ECMASCRIPE的一种实现,与JavaScript平级