You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Azure Function返回列表或二维结构?求示例代码指引

Returning Lists/Multi-Dimensional Structures from Azure Functions

Is this feasible?

Absolutely! Azure Functions makes returning lists, arrays, or nested 2D structures totally straightforward—its runtime natively handles JSON serialization for you out of the box. Whether you’re building an HTTP-triggered function that sends data back to a client, or outputting structured data to other Azure services, this approach works seamlessly.

Example 1: Return a Simple List (C# HTTP Trigger)

Here’s a basic HTTP-triggered function that returns a list of strings. The framework automatically converts the list to a JSON array in the response:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;

namespace ListReturnFunction
{
    public static class GetItemList
    {
        [FunctionName("GetItemList")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Fetching and returning item list.");
            
            // Create a sample list of items
            var itemList = new List<string>
            {
                "Wireless Headphones",
                "Portable Charger",
                "Bluetooth Speaker"
            };
            
            // Return the list directly—no manual JSON serialization needed
            return new OkObjectResult(itemList);
        }
    }
}

When you call this function, the response will be a clean JSON array:

["Wireless Headphones","Portable Charger","Bluetooth Speaker"]

Example 2: Return a Multi-Dimensional Structure (C#)

If you need to return a nested 2D structure (like a list of custom objects), the process is identical. Here’s an example returning a list of product records:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;

namespace NestedStructureFunction
{
    // Custom class to represent a product
    public class Product
    {
        public string ProductId { get; set; }
        public string ProductName { get; set; }
        public decimal Price { get; set; }
        public bool InStock { get; set; }
    }

    public static class GetProductList
    {
        [FunctionName("GetProductList")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Returning list of products.");
            
            var productList = new List<Product>
            {
                new Product { ProductId = "PROD-001", ProductName = "Smartphone", Price = 699.99m, InStock = true },
                new Product { ProductId = "PROD-002", ProductName = "Tablet", Price = 399.99m, InStock = false },
                new Product { ProductId = "PROD-003", ProductName = "Smart Watch", Price = 199.99m, InStock = true }
            };
            
            return new OkObjectResult(productList);
        }
    }
}

The response will be a JSON array of objects (a classic 2D structured format):

[
    {"ProductId":"PROD-001","ProductName":"Smartphone","Price":699.99,"InStock":true},
    {"ProductId":"PROD-002","ProductName":"Tablet","Price":399.99,"InStock":false},
    {"ProductId":"PROD-003","ProductName":"Smart Watch","Price":199.99,"InStock":true}
]

Example 3: Return Lists in Python HTTP Trigger

For Python developers, the workflow is just as simple. You can serialize lists or nested structures to JSON and return them with the correct content type:

import azure.functions as func
import logging

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="return_grocery_list")
def return_grocery_list(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Returning grocery list from Python function.')
    
    grocery_list = ["Milk", "Eggs", "Bread", "Fresh Vegetables"]
    
    # Serialize list to JSON and return with correct header
    return func.HttpResponse(
        body=func.Json.dumps(grocery_list),
        mimetype="application/json",
        status_code=200
    )

# Example of returning a nested 2D structure
@app.route(route="return_order_details")
def return_order_details(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Returning nested order details.')
    
    order_data = [
        {"order_id": "ORD-1001", "items": [{"name": "Laptop", "quantity": 1}, {"name": "Mouse", "quantity": 2}]},
        {"order_id": "ORD-1002", "items": [{"name": "Keyboard", "quantity": 1}, {"name": "Monitor", "quantity": 1}]}
    ]
    
    return func.HttpResponse(
        body=func.Json.dumps(order_data),
        mimetype="application/json",
        status_code=200
    )

Quick Tips

  • For C#, using OkObjectResult ensures the response has the correct application/json content type and status code.
  • For Python, always use func.Json.dumps() to serialize collections—this handles edge cases like special characters properly.
  • Avoid circular references in your objects/structures, as these will break JSON serialization.

内容的提问来源于stack exchange,提问作者user576510

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:58:58