Json本质上一个带有特定格式的字符串,json是一种在各个编程语言中流通的数据格式,负责不同编程语言的数据传递和交互。类似于:
# 准备一个列表,列表中每个元素都是字典,将其转换为JSON
data = [{"name":"Bob","age":20},{"name":"Alice","age":21},{"name":"Jack","age":22}]
json_str = json.dumps(data)
print(type(json_str))
print(json_str)
# JSON 是一个特殊格式的字符串
# 准备一个字典,将字典转换为字符串
data = {"name":"库里","age":20,"gender":"male"}
json_str = json.dumps(data,ensure_ascii=False) # ensure_ascii = False 设置中文编码格式
print(type(json_str))
print(json_str)
# 将JSON 字符串转换为Python数据类型[{K:v,k:v},{k:v,k:v}]
s = '[{"name":"库里","age":20,"gender":"male"},{"name":"詹姆斯","age":21,"gender":"famale"}]'
json_data = json.loads(s)
print(type(json_data))
print(json_data)
# 将JSON 字符串转换为python数据类型{k:v,k:v}
s = '{"name":"库里","age":20,"gender":"male"}'
json_data = json.loads(s)
print(type(json_data))
print(json_data)