How do I return JSON from an Azure Function
Here's a full example of an Azure function returning a properly formatted JSON object instead of XML:
#r "Newtonsoft.Json"using System.Net;using Newtonsoft.Json;using System.Text;public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log){ var myObj = new {name = "thomas", location = "Denver"}; var jsonToReturn = JsonConvert.SerializeObject(myObj); return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json") };}
Navigate to the endpoint in a browser and you will see:
{ "name": "thomas", "location": "Denver"}
The easiest way is perhaps to
public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "/jsontestapi")] HttpRequest req, ILogger log){ return new JsonResult(resultObject);}
Will set the content-type to application/json
and return the json in the response body.
You can take req
from
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
and create the response using
return req.CreateResponse(HttpStatusCode.OK, json, "application/json");
or any of the other overloads in assembly System.Web.Http
.
More info on docs.microsoft.com