搞懂Python存储和交换数据的用法
导入 json 模块
import json
json.dumps(): 对数据进行编码。
json.loads(): 对数据进行解码。
Python | JSON |
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON | Python |
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
# 导入 json 模块
import json
x = '{ "name":"Jack", "age":26, "sex":"woman"}'
# 解析 x:
y = json.loads(x)
# 结果是 Python 字典:
print(["name"])
['name']
# 导入 json 模块
import json
x = { "name":"Jack", "age":26, "sex":"woman"}
# 转换为 JSON:
y = json.dumps(x)
# 结果是 JSON 字符串:
print(y)
{"name": "Jack", "age": 26, "sex": "woman"}
dict
list
tuple
string
int
float
True
False
None
# 导入 json 模块
import json
print(json.dumps({"name": "Jack", "age": 18}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
{"age": 18, "name": "Jack"}
["apple", "bananas"]
["apple", "bananas"]
"hello"
42
31.76
true
false
null
# 导入 json 模块
import json
x = { "name":"Jack", "age":26, "sex":"woman"}
# 格式化JSON字符串
print(json.dumps(x, indent=4))
{
"age": 26,
"name": "Jack",
"sex": "woman"
}
# 导入 json 模块
import json
x = { "name":"Jack", "age":26, "sex":"woman"}
# 分隔JSON字符串
print(json.dumps(x, indent=4, separators=(". ", " = ")))
{
"age" = 26,
"name" = "Jack",
"sex" = "woman"
}
# 导入 json 模块
import json
x = { "name":"Jack", "age":26, "sex":"woman"}
# 分隔JSON字符串
print(json.dumps(x, indent=4, sort_keys=True))
{
"age" = 26,
"name" = "Jack",
"sex" = "woman"
}