4
$\begingroup$

I am trying to get an APIFunction to send valid JSON. This is my demo function.

CloudDeploy[
 APIFunction[{"y" -> "Number"}, 
  ExportString[{"TestData" -> {"bob1" -> #y, "bob2" -> "abc"}}, 
    "JSON", "Compact" -> True] &], "EPCtest3", 
 Permissions -> "Public"]

Run from a URL, e.g."www.wolfram. ... /EPCtest3?y=123" produces this

"{\"TestData\":{\"bob1\":123,\"bob2\":\"abc\"}}"

However, this JSON validator says it is invalid. It is ok if formatted like so:

{"TestData":{"bob1":123,"bob2":"abc"}}

The receiving code is expecting JSON, e.g.

var documentResponse = await apiResponse.Content.ReadAsStringAsync();
dynamic response = JsonConvert.DeserializeObject(documentResponse);

I can output valid JSON in regular Mathematica using the Notation package, (not ideal though). However, that doesn't work from the cloud.

Needs["Notation`"]
InfixNotation[ParsedBoxWrapper[":"], Rule ]
{"TestData" -> {"bob1" -> 123, "bob2" -> "abc"}}
{"TestData" : {"bob1" : 123, "bob2" : "abc"}}

E.g. Doesn't work on the cloud.

enter image description here

Any help on sending JSON from the APIFunction appreciated.

$\endgroup$
  • 2
    $\begingroup$ You need to specify "String" as result type for the APIFunction, as in APIFunction[{"y" -> "Number"}, ExportString[...] &, "String"]. Otherwise you will get the input-form like representation of the resulting string $\endgroup$ – Lukas Lang Sep 19 at 10:46
  • $\begingroup$ Great! Thanks.:-) $\endgroup$ – Chris Degnen Sep 19 at 10:54
2
$\begingroup$

As Lukas Lang said,

You need to specify "String" as result type for the APIFunction, as in APIFunction[{"y" -> "Number"}, ExportString[...] &, "String"]. Otherwise you will get the input-form like representation of the resulting string.

The function now works:

CloudDeploy[
 APIFunction[{"y" -> "Number"}, 
  ExportString[{"TestData" -> {"bob1" -> #y, "bob2" -> "abc"}}, 
    "JSON", "Compact" -> True] &, "String"], "EPCtest3", 
 Permissions -> "Public"]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.