JSON:
JavaScript Object Notation (JavaScript对象标记), 是一种轻量级的数据交换格式
字符串是JSON的表现形式
优点: 易于阅读,易于解析,网络传输效率高,跨语言交换数据
实例一:json object 字符串
import json
# 定义一个json 字符串
json_str = '{"name":"ciellee", "age":20}'
#反序列化 将json字符串转换为字典
student = json.loads(json_str)
print(type(student))
print(student)
print(student['name'])
输出结果如下:
<class 'dict'>
{'name': 'ciellee', 'age': 20}
ciellee
实例二:json object array
import json
# 定义一个json字符串
json_str = '[{"name":"ciellee","age":20,"flag":false},{"name":"XUE", "age":18}]'
#反序列化 将json字符串转换为字典
student = json.loads(json_str)
print(type(student))
print(student)
输出结果如下:
<class 'list'>
[{'name': 'ciellee', 'age': 20, 'flag': False}, {'name': 'XUE', 'age': 18}]
JSON 和 Python 的数据类型转换
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number | int |
number | float |
true | True |
false | False |
null | None |
反序列化: JSON => Python
序列化: Python => JSON
实例三:序列化
import json
# 序列化 python -> json
student = [
{'name':'ciellee','age':20,'flag':False},
{'name':'XUE','age':18}
]
json_str = json.dumps(student)
print(type(json_str))
print(json_str)
输出结果为:
<class 'str'>
[{"name": "ciellee", "age": 20, "flag": false}, {"name": "XUE", "age": 18}]