redconservatory
redconservatory

Reputation: 21924

Get Coldfusion to parse a json request

I have a javascript object:

data = { color: red, day: monday, list: {1,2,3,4,5,6}}

I pass this to a coldfusion page using jQuery:

$.ajax({
                type: "POST",
                url: "ajax_myPage.cfm",
                data: JSON.stringify(data),
                contentType: "application/json",
                dataType: "json" });

This is my cfdump:

enter image description here

(the "list" is actually going to contain a list of emails but I am just testing with one address right now)

In coldfusion, I am trying to assign each "part" to a variable:

<cfset requestBody = toString( getHttpRequestData().content ) />
<!--- Double-check to make sure it's a JSON value. --->
<cfif !isJSON( requestBody )>

<!--- Echo back POST data. --->
<h3>The URL you requested does not provide valid JSON</h3>
<cfdump
var="#requestBody#"
label="HTTP Body"
/>
<cfelse>
 <cfset cfData=DeserializeJSON(requestBody)>
 <cfset color = cfData.color>
 <cfset day = cfData.day>
 <cfset myList = cfData.list>
</cfif>

However I am getting an error with "list",

Complex object types cannot be converted to simple values. 

How do I parse the list as Coldfusion?

Upvotes: 7

Views: 6472

Answers (1)

Kevin B
Kevin B

Reputation: 95031

i would have sent the data as a post var,

data: { json: JSON.stringify(data) }

and then parsed it into a variable:

<cfset structJSON = deserializeJSON(FORM.json)>

At that point, cfdump the structure to inspect it's contents so that you know how to access them.

Since we don't know what the json structure you are passing to ColdFusion consists of, I have no idea what structJSON.list contains or why it would be throwing an error.

Edit: Ah i see your json now.

Your list is not valid json, change { and } to [ and ].

data = { color: "red", day: "monday", list: [1,2,3,4,5,6]}

Upvotes: 12

Related Questions