python学习笔记(一)JSON
JSON是什么?
JSON 是用于存储和交换数据的语法。
怎样使用JSON?
JSON-——》python数据类型
import json
# 一些 JSON:
x = '{ "name":"Bill", "age":63, "city":"Seatle"}'
# 解析 x:
y = json.loads(x)#对json类型进行解析
# 结果是 Python 字典:
print(y["age"])#63
python数据类型-——》JSON
import json
# Python 对象(字典):
x = {
"name": "Bill",
"age": 63,
"city": "Seatle"
}
# 转换为 JSON:
y = json.dumps(x)
# 结果是 JSON 字符串:
print(y)#{"name": "Bill", "age": 63, "city": "Seatle"}
当 Python 转换为 JSON 时,Python 对象会被转换为 JSON不同类型
Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null
- json.dumps()打印出来是一行,不容易读
json.dumps(x, indent=4)
- 确认分割符号
json.dumps(x, indent=4, separators=(". ", " = "))
#{
"name" = "Bill".
"age" = 63.
"married" = true.
"divorced" = false.
"children" = [
"Jennifer".
"Rory".
"Phoebe"
].
"pets" = null.
"cars" = [
{
"model" = "Porsche".
"mpg" = 38.2
}.
{
"model" = "BMW M5".
"mpg" = 26.9
}
]
- json.dumps() 方法提供了对结果中的键进行排序的参数:
json.dumps(x, indent=4, sort_keys=True)
这篇博客介绍了Python中的JSON处理,包括JSON的基本概念、如何将Python数据类型转化为JSON以及JSON到Python的转换。主要关注json.dumps()方法在序列化过程中的应用。


被折叠的 条评论
为什么被折叠?



