Konstantin Schütte
Konstantin Schütte

Reputation: 1009

returning a JSON object

is there any way to return a real JSON object through a function in ColdFusion? My current solution is to turn a query into a string and in another CF-file I'm converting it back to a JSON object:

<cffunction name="addLicense" access="remote" returntype="string" returnFormat="JSON" httpmethod="POST">
  <cfquery datasource="hostmanager" name="createCustomer">
    SELECT * FROM license
  </cfquery>
  <cfreturn serializeJSON(createCustomer)>
</cffunction>

Upvotes: 3

Views: 969

Answers (4)

Konstantin Sch&#252;tte
Konstantin Sch&#252;tte

Reputation: 1009

Now I'm using this solution to return JSON:

returntype="any" produces="application/json"

Upvotes: 2

Simon Fermor
Simon Fermor

Reputation: 116

You could use returnType="query" and the function will return the results in JSON format. You might need to use <cfcontent type="application/json"> to make sure the returned content type is correct.

Upvotes: 1

James A Mohler
James A Mohler

Reputation: 11120

There are many different ways to use serializeJSON

<cfscript>
    myQuery = queryNew("id,name,amount","Integer,Varchar,Integer", 
                [ 
                        {id=1,name="One",amount=15}, 
                        {id=2,name="Two",amount=18}, 
                        {id=3,name="Three",amount=32} 
                ]); 
    writeOutput("The new query is:")
    writeDump(myQuery)
</cfscript>

<cfoutput>
    <h4>Default</h4>
    <p><code>#serializeJSON(myQuery)#</code></p>
    <h4>Row</h4>
    <p><code>#serializeJSON(myQuery, "row")#</code></p>
     <h4>Column</h4>
    <p><code>#serializeJSON(myQuery, "column")#</code></p>
     <h4>Struct</h4>
    <p><code>#serializeJSON(myQuery, "struct")#</code></p>
</cfoutput>

Which Results in

enter image description here

See: https://cffiddle.org/app/file?filepath=58f7cee2-dabb-42f8-91ef-7dd41e1691c0/49ad94cb-23e4-4c9c-9986-b7c1d4c15e3a/c818a99e-4476-4625-8bec-657bcfa9b0e2.cfm

Upvotes: 5

rrk
rrk

Reputation: 15846

In ColdFusion2016 I use something like this.

deserializeJSON(serializeJSON(createCustomer, 'struct'))

This basically give you an array of structures(with query columns as struct keys).

Upvotes: 3

Related Questions