从Python转换为JSON
如果您有Python对象,则可以使用json.dumps()方法将其转换为JSON字符串。
从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)
- 元组(tuple)
- 字符串(str)
- 整型(int)
- 浮点(float)
- True
- False
- 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):
Python |
JSON |
dict |
Object |
list |
Array |
tuple |
Array |
str |
String |
int |
Number |
float |
Number |
True |
true |
False |
false |
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))
尝试一下