Description
Converts a JSON-encoded string to a JavaScript variable.
Function syntax
ColdFusion.JSON.decode(string) |
See also
ColdFusion.JSON.encode, DeserializeJSON, SerializeJSON, Using Ajax Data and Development Features in the Developing ColdFusion Applications, http://www.json.org
History
ColdFusion 8: Added this function
Parameters
Parameter |
Description |
---|---|
string |
The string to encode. |
Returns
A Javascript variable containing the data in the JSON encoded string.
Usage
Use this function when you must explicitly convert between JavaScript and JSON format, for example, when you must call a remote function that is not in a CFC.If the JSON string has a security prefix as defined by the Server Settings > Settings page of the ColdFusion Administrator or specified in the cfapplication or cffunction tags, the function strips the prefix before decoding the string.
Example
The following example uses the ColdFusion.JSON.decode and ColdFusion.JSON.encode functions When the user clicks the "Call" link, the callMe function encodes the String as JSON and calls the echo CFC's plainEcho function with the result. The function also sets the return format to plain, so that the CFC function does not automatically convert its return value to JSON, and sends plain text instead.The echo.cfc component has two functions:
- The plainEcho function converts its argument from JSON to a ColdFusion variable, calls the echo function, converts the result to JSON, and returns it to the caller.
The echo function creates a structure, sets the structure's entry to the input parameter, and returns the result. (You could call this function remotely using to see the result of calling a function that does not encode JSON when you request a plain return type. To see the results, use the cfdebug HTTP parameter when you run the main page.)The main page has the following lines:
<cfajaxproxy cfc="echo">
<cfajaximport>
<html>
<head>
<script>
function callme()
{
var e = new echo();
e.setReturnFormat('plain');
var args = {a:"Hello again!"};
var argsJSON = ColdFusion.JSON.encode(args);
var json = e.plainEcho(argsJSON);
var o = ColdFusion.JSON.decode(json);
alert(o.A);
}
</script>
</head>
<body>
<a href="javascript:callme()">Call</a>
</body>
</html>The echo.cfc file has the following lines:
<cfcomponent output="false">
<cffunction name="echo" access="remote">
<cfargument name="text">
<cfset var ret = StructNew()>
<cfset ret.a = text>
<cfreturn ret>
</cffunction>
<cffunction name="plainEcho" access="remote">
<cfargument name="text">
<cfset t = deserializeJSON(text)>
<cfset ret = echo(t.A)>
<cfreturn serializeJSON(ret)>
</cffunction>
</cfcomponent>