1、从Python对象转换成JSON
如果有Python对象,则可以使用json.dumps()
方法将其转换为JSON字符串。
例如:
从Python对象转换为JSON:
import json # a Python object (dict):x = '{ "name":"cjavapy", "age":3, "city":"china"}'
# convert into JSON: y = json.dumps(x) #结果是 JSON string: print(y)
下列类型可以转换Python对象成JSON字符串:
- dict
- list
- tuple
- string
- int
- float
- True
- False
- None
例如:
将Python对象转换为JSON字符串,并输出值:
import json print(json.dumps({"name": "cjavapy", "age": 3})) print(json.dumps(["python", "cjavapy"])) print(json.dumps(("python", "cjavapy"))) 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": "python", "age": 20, "married": True, "divorced": False, "children": ("c","python"), "pets": None, "langs": [ {"model": "java", "year": 5}, {"model": "python", "year": 6} ] } print(json.dumps(x))
相关文档: