如何从Python函数返回一个 json 对象?
的完整形式 JSON 是 JavaScript 对象表示法。这意味着由编程语言中的文本组成的脚本(可执行)文件用于存储和传输数据。 Python通过一个名为 json 的内置包支持 JSON,该模块可用于将Python字典转换为 JSON 对象。在Python中字典用于获取其等效的 JSON 对象。
方法:
- 导入模块
- 创建函数
- 创建字典
- 使用dumps()方法将字典转换为 JSON 对象
- 返回 JSON 对象
Syntax: json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
下面给出使用上述方法的实现:
示例 1:
Python3
# Import Module
import json
# Create geeks function
def geeks():
# Define Variable
language = "Python"
company = "GeeksForGeeks"
Itemid = 1
price = 0.00
# Create Dictionary
value = {
"language": language,
"company": company,
"Itemid": Itemid,
"price": price
}
# Dictionary to JSON Object using dumps() method
# Return JSON Object
return json.dumps(value)
# Call Function and Print it.
print(geeks())
Python3
# Import Module
import json
# Create geeks function
def geeks():
# Create Dictionary
value = {
"firstName": "Pawan",
"lastName": "Gupta",
"hobbies": ["playing", "problem solving", "coding"],
"age": 20,
"children": [
{
"firstName": "mohan",
"lastName": "bansal",
"age": 15
},
{
"firstName": "prerna",
"lastName": "Doe",
"age": 18
}
]
}
# Dictionary to JSON Object using dumps() method
# Return JSON Object
return json.dumps(value)
# Call Function and Print it.
print(geeks())
输出:
{“language”: “Python”, “company”: “GeeksForGeeks”, “Itemid”: 1, “price”: 0.0}
示例 2:使用列表作为字典值。
蟒蛇3
# Import Module
import json
# Create geeks function
def geeks():
# Create Dictionary
value = {
"firstName": "Pawan",
"lastName": "Gupta",
"hobbies": ["playing", "problem solving", "coding"],
"age": 20,
"children": [
{
"firstName": "mohan",
"lastName": "bansal",
"age": 15
},
{
"firstName": "prerna",
"lastName": "Doe",
"age": 18
}
]
}
# Dictionary to JSON Object using dumps() method
# Return JSON Object
return json.dumps(value)
# Call Function and Print it.
print(geeks())
输出:
{“firstName”: “Pawan”, “lastName”: “Gupta”, “hobbies”: [“playing”, “problem solving”, “coding”], “age”: 20, “children”: [{“firstName”: “mohan”, “lastName”: “bansal”, “age”: 15}, {“firstName”: “prerna”, “lastName”: “Doe”, “age”: 18}]}