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
  • 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$ Commented Sep 19, 2019 at 10:46
  • $\begingroup$ Great! Thanks.:-) $\endgroup$ Commented Sep 19, 2019 at 10:54

1 Answer 1

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$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.