3
\$\begingroup\$

I am trying to generate JSON from a query. All this seems to be too much grinding it out.

string function getJSON() output="false" { 
 var result = "[";
 var myrow = 0;
 for(var row in this.qryLocation) {
 myrow++;
 result &= "[" 
 & row.LocationID & ',' 
 & '"' & row.Address & " " & row.City & '",' 
 & '"' & row.formatted_CreateDate & '"'
 & ']' 
 & myRow < this.qryLocation.recordcount ? ',' : ''; 
 } // end for-in query
 return result & "]"; 
 }

All this seems very hard to read, especially making sure that the last row does not get an extra comma.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 2, 2015 at 2:04
\$\endgroup\$
5
  • \$\begingroup\$ That does seem quite clunky. I'm sure someone will have ideas on making this more readable and practical. \$\endgroup\$ Commented Sep 2, 2015 at 2:17
  • \$\begingroup\$ Which version of ColdFusion? \$\endgroup\$ Commented Sep 2, 2015 at 5:27
  • 3
    \$\begingroup\$ It's difficult to answer well without knowing your version of CF, but as a practice: don't build a JSON string by hand: build a native data structure which represents the format you need, then serialise it to JSON when done. \$\endgroup\$ Commented Sep 2, 2015 at 6:57
  • \$\begingroup\$ I am on ColdFusion 11 \$\endgroup\$ Commented Sep 2, 2015 at 15:33
  • \$\begingroup\$ The data comes from the result of a CFquery \$\endgroup\$ Commented Sep 2, 2015 at 15:34

1 Answer 1

3
\$\begingroup\$

I agree with Adam's comment. Generally, you should avoid rolling-your-own JSON. Just create native CF objects as usual (ie CF arrays and structures). Then use SerializeJSON to generate the JSON string.

SerializeJSON eliminates the need for manual quoting, which dramatically improves the readability of the code IMO. It also handles any escaping of object values automatically (the current code does not). Granted, Adobe's SerializeJSON function does have a few .. "quirks". So you may prefer to use a different implementation. However, the basic approach remains the same.

string function getJSON() output="false" { 
 var result = [];
 for(var row in this.qryLocation) {
 arrayAppend(result, [ row.LocationID, row.Address & " " & row.City, row.formatted_CreateDate ] );
 } 
 return serializeJSON(result); 
}
answered Dec 4, 2015 at 20:43
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.