当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Prevent ColdFusion from converting string to number using SerializeJSON

问题描述:

I have ColdFusion 9.0.1 with the latest hotfix (4).

I need ColdFusion to return all JSON data with quotes around them (as strings). I have the following problem:

<cfset test = StructNew()>

<cfset test.name = "1234.100">

<cfoutput>#SerializeJSON(test)#</cfoutput>

The text that is outputted is:

{"name":1234.100}

Every javascript JSON parser converts that to 1234.1 and is not keeping the trailing 0's. I either need ColdFusion to output as string or a javascript parser to keep the trailing 0's. Any ideas?

This is a simplified example. I am grabbing this data from a database.

网友答案:

Here's a solution - albeit a very hacky, inelegant solution...

Your setup:

var test = {
  name = "1234.100"
};

Adding some obvious string to the front forces the value to become a string when it is converted to JSON. Then we get rid of this ugly string.

var thisIsSuchAHorribleHack = "([email protected][email protected]$)";
test.name = thisIsSuchAHorribleHack & test.name;
var serializedTest = SerializeJSON(test);
serializedTest = Replace(serializedTest, thisIsSuchAHorribleHack, "", "ALL");
writeOutput(serializedTest);
网友答案:

We've had a lot of luck using Jackson to get round the nightmare that is CF json handling.

网友答案:

Just add a simple whitespace at the beginning of your number. I tried doing it at the end but it doesn't work.

<cfset test = StructNew()>
<cfset test.name = " 1234.100">
<cfoutput>#SerializeJSON(test)#</cfoutput>

The output will be

{"name":" 1234.100"}
网友答案:

If you don't want to use a kludge, you can use a third party library that encodes JSON correctly. I used JSONUtil from http://jsonutil.riaforge.org/. I am using ColdFusion 9 so I don't know if the more recent versions of ColdFusion have fixed some of the encoding abnormalities.

分享给朋友:
您可能感兴趣的文章:
随机阅读: