Skip to main content
Inspiring
December 11, 2013
Question

How to POST JSON to CFHTTP

  • December 11, 2013
  • 1 reply
  • 4507 views

Hi,

I need help to write RESTful cfc to accept call from jquery in JSON format.

This is approximate format of the structure as an argument to the cfc:

returns:

code: 200  // Successfull

data: {

    "success": true,

    "result": {

        "questions":[

            {"question_id": "1", "question_answert": "some text..."},

            {"question_id": "2", "question_answer": "some text..."},

            ...

            {"question_id": "3", "question_answer": "some text..."}

        ]

    }

}

This is cfc to parse JSON:

<cffunction output="yes" name="verifyQuestions" access="remote" produces="application/json" returnType="string" httpmethod="post">

              <cfargument name="questanswers" type="string" restargsource="path"/>

        <cfset cfData = DeserializeJSON(questanswers)>

        <cfset colList = ArrayToList(cfData.COLUMNS)>

        <cfset qIdx = ListFind(colList, "question_id")>

        <cfset aIdx = ListFind(colList, "question_answer")>

          <!--- loop through the structure and validate it here against db --->

        <cfloop index="i" from="1" to="3">

            question id: #cfData.DATA[qIdx]#

            answer: #cfData.DATA[aIdx]#

        </cfloop>

        <cfreturn VARIABLES.vcDeserilized>

    </cffunction>

This is a cfm file to test RESTful cfc:

<cfhttp url="http://10.200.5.2/rest/login/questions/" method="post">

<cfhttpparam type="formfield" value="[{question_id:'4', question_answer:'test 4'},{question_id:'6', question_answer:'test 6'},{question_id:'8', question_answer:'test 8'}]" name="questanswers">

</cfhttp>

<cfoutput>#cfhttp.filecontent#</cfoutput>

When run the file above I am getting

{"Message":"JSON parsing failure: Expected '\"' at character 3:'q' in [{question_id:'4', question_answer:'test 4'},{question_id:'6', question_answer:'test 6'},{question_id:'8', question_answer:'test 8'}]"}

Also, from what I understand debug from RESTful cfc's is problematic. Does my cfc syntax look correct to accept JSON formatted object?

Thanks,

Gena

This topic has been closed for replies.

1 reply

pete_freitag
Participating Frequently
December 11, 2013

The JSON that you are sending in the cfhttpparam is invalid, test the string out with IsJSON or use a tool like http://jsonlint.com/ to find the error.