Friday 19 February 2016

ColdFusion 2016: toJson() method

G'day:
This'll need to be super quick as I only have 15min of lunch break left.

ColdFusion 2016 added a toJson() method to allmost of its inbuilt types. Here's the biz:

a = ["tahi"];
st = {two="rua"};
ost = {three="toru"};
q = queryNew("en,mi", "varchar,varchar",[["four","wha"]]);
cfxml(variable="x"){
    writeOutput("<five><rima/></five>");
}
s = "ono";
ts = now();
d = 42 * 1;
b = true == true;

CLI.writeLn(a.toJson());
CLI.writeLn(st.toJson());
CLI.writeLn(ost.toJson());
CLI.writeLn(q.toJson());
CLI.writeLn(q.toJson(true));
CLI.writeLn(x.toJson());
CLI.writeLn(ts.toJson());
//CLI.writeLn(d.toJson()); // not supported for numerics
//CLI.writeLn(b.toJson()); // not supported for booleans
CLI.writeLn(variables.toJson());


And the output:


C:\src\CF12\other\tojson>cf toJson.cfm
["tahi"]
{"TWO":"rua"}
{"THREE":"toru"}
{"COLUMNS":["EN","MI"],"DATA":[["four","wha"]]}
{"ROWCOUNT":1,"COLUMNS":["EN","MI"],"DATA":{"EN":["four"],"MI":["wha"]}}
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<five><rima/></five>"
"ono"
"February, 19 2016 13:48:38"
{"OST":{"THREE":"toru"},"B":true,"ST":{"TWO":"rua"},"X":"<?xml version=\"1.0\" e
ncoding=\"UTF-8\"?>\n<five><rima/></five>","Q":{"COLUMNS":["EN","MI"],"DATA":[["
four","wha"]]},"D":42.0,"TS":"February, 19 2016 13:48:38","A":["tahi"]}
C:\src\CF12\other\tojson>

So all good for arrays, structs, ordered structs, queries (and both modes for queries), XML, strings, dates and scopes. But it fails on numerics and booleans. For the sake of completeness it should work on numerics and booleans too (esp if it works on strings!). I've raised 4119888.

Anyway... well done: something that's a) useful; b) almost works 100%. And the non-100% it's quite edge-case-y anyone.

Righto.

--
Adam