在API平台中,返回数据类型可以是多种形式,常见的有以下几种:
import json
def get_data():
# 获取数据的逻辑
data = {'name': 'John', 'age': 30, 'city': 'New York'}
return json.dumps(data)
# 调用API接口
result = get_data()
print(result)
输出结果为:{"name": "John", "age": 30, "city": "New York"}
from xml.etree.ElementTree import Element, SubElement, tostring
def get_data():
# 获取数据的逻辑
root = Element('data')
name = SubElement(root, 'name')
name.text = 'John'
age = SubElement(root, 'age')
age.text = '30'
city = SubElement(root, 'city')
city.text = 'New York'
return tostring(root, encoding='unicode')
# 调用API接口
result = get_data()
print(result)
输出结果为:
John
30
New York
import csv
def get_data():
# 获取数据的逻辑
data = [['name', 'age', 'city'], ['John', 30, 'New York']]
return '\n'.join([','.join(map(str, row)) for row in data])
# 调用API接口
result = get_data()
print(result)
输出结果为:
name,age,city
John,30,New York
根据需要选择适合的数据格式,并根据实际业务逻辑进行数据的组装和返回。