Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 677
redconservatory Avatar asked Jan 25 '12 20:01

redconservatory


People also ask

How do I deserialize JSON in ColdFusion?

The DeserializeJSON function converts each JSON data type directly into the equivalent ColdFusion data type, as follows: If the strictMapping parameter is true (the default), all JSON objects become CFML structures.

How do I deserialize JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

Which function is used to serialize an object into a JSON string?

The SerializeJSON function converts all other ColdFusion data types to the corresponding JSON types. It converts structures to JSON Objects, arrays to JSON Arrays, numbers to JSON Numbers, and strings to JSON Strings.


1 Answers

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]}
like image 108
Kevin B Avatar answered Nov 09 '22 17:11

Kevin B