simonalexander2005
simonalexander2005

Reputation: 4579

Why does this azure function produce a JSON output?

I am following a tutorial for creating an Azure app, part of which cleans up the html from the body of an email: https://learn.microsoft.com/en-us/azure/logic-apps/tutorial-process-email-attachments-workflow#create-function-to-clean-html

The relevant section is as follows:

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Text.RegularExpressions;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log) {

   log.LogInformation("HttpWebhook triggered");

   // Parse query parameter
   string emailBodyContent = await new StreamReader(req.Body).ReadToEndAsync();

   // Replace HTML with other characters
   string updatedBody = Regex.Replace(emailBodyContent, "<.*?>", string.Empty);
   updatedBody = updatedBody.Replace("\\r\\n", " ");
   updatedBody = updatedBody.Replace(@"&nbsp;", " ");

   // Return cleaned text
   return (ActionResult)new OkObjectResult(new { updatedBody });
}

The following test input: {"name": "<p><p>Testing my function</br></p></p>"}

is expected to give the following output: {"updatedBody":"{\"name\": \"Testing my function\"}"}

Why is the output wrapped in {"updatedBody":} json?

As far as I can see from looking at the code, the output is provided as a string array, using an object called updatedBody to populate the only element in the array (return (ActionResult)new OkObjectResult(new { updatedBody });) - but it looks like instead the { updatedBody } is treated as a json array somehow?

Upvotes: 0

Views: 1082

Answers (1)

gunr2171
gunr2171

Reputation: 17510

The parameter of OkObjectResult is an object. That class is responsible (along with the underlying azure function / asp.net core pipeline) for serializing that data into a string, and adding it to the HTTP response content. (There are some special cases like when the data you pass in is a string, but that's not important now)

The serialization is done for you after the method has concluded. You don't need to worry about it. The framework takes care of it.

That's why your JSON has a wrapped "updatedBody" property. If I have the following code:

string myValue = "yes";
return OkObjectResult(new {
  myValue
});

I'd get the following JSON

{
  "myValue": "yes"
}

You can change the property name as well

string myValue = "yes";
return OkObjectResult(new {
  message = myValue
});
{
  "message": "yes"
}

This is how JSON.Net (the c# library) and Microsoft's System.Text.Json libraries work, and OkObjectResult uses this behind the scenes.

Upvotes: 1

Related Questions