Python/gloss python convert into JSON
来自菜鸟教程
<languages />
Python从Python转换为JSON
从Python转换为JSON
如果您有Python对象,则可以使用来将其转换为JSON字符串。
json.dumps()
方法。
例
从Python转换为JSON:
import json
# a Python object (dict):
x = {
"name":
"John",
"age": 30,
"city": "New York"
}
#
convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
您可以将以下类型的Python对象转换为JSON字符串:
- dict
- list
- 元组
- 串
- int
- 浮动
- True
- 假
- None
例
将Python对象转换为JSON字符串,并输出值:
import json
print(json.dumps({"name": "John", "age": 30}))
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))
从Python转换为JSON时,Python对象将转换为等效的JSON(JavaScript):
| 蟒蛇 | JSON |
|---|---|
| dict | 宾语 |
| list | 排列 |
| 元组 | 排列 |
| str | 串 |
| int | 数 |
| 浮动 | 数 |
| True | true |
| 假 | 假 |
| None | null |
例
转换包含所有合法数据类型的Python对象:
import json
x = {
"name":
"John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets":
None,
"cars": [
{"model": "BMW 230", "mpg":
27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))