0

I want to use JSON.stringify() to convert my JS object to a json string. But when I use richfaces components in the web page, I got the wrong result. See the example below. Please help me. Thank you! this is the codes:

function testJSON()
{
var selArray = new Array();
selArray.push("aaa");
selArray.push("bbb");
selArray.push("ccc");
alert(JSON.stringify(selArray));
}

I got this if there is no richfaces components in the page.

["aaa","bbb","ccc"]

And if there is any richfaces component like "rich:modalpanel" in the page, it will get the following wrong JSON string.

"[\"aaa\",\"bbb\",\"ccc\"]"

I think that's because richfaces has done songthing that affected JSON.

So what can I do to avoid the effect of richfaces ?

Thank you very much!

Marc B
  • 356,200
  • 43
  • 426
  • 500
Wynn
  • 11
  • 1
  • 1
    Actually, the first is an array not a string. The second is an actual string with escaped quotes. If you called JSON.stringify, the second output is correct and the first is not. JSON.stringify converts a json object to a string not an array. – War10ck Jan 28 '13 at 14:24
  • remember, given `var x = y`, json is pretty much literally whatever `y` is - it's the equivalent of the right-hand-side in an assignment operator with a few minor syntax differences. – Marc B Jan 28 '13 at 14:25
  • but when I don't use richfaces component, JSON.stringigy gernerates the first result which is the result I actually expected. I want to pass the JSON string that is generated by JSON to the backend java bean and parse the json string using java json lib to get a array of string. How can I achive this with richfaces component used? – Wynn Jan 28 '13 at 14:59
  • 1
    I'm not sure how you would achieve this in java. Just to note though, the first result may be what you want, but it is not the correct return result for JSON.stringify. Unless, you provide a replacer function that alters the object itself, stringify should return a string not an array. – War10ck Jan 28 '13 at 15:17
  • It looks like RichFaces is trying to give you a hand (and it does a good job), just look the [stringify definition and example](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify). Maybe you would explain what do want/need and add the JSF and RF version you're working with (it looks like JSF 1.2 and RF 3.3). – Luiggi Mendoza Jan 28 '13 at 22:15

1 Answers1

1

Perhaps you are running into this issue, since Richfaces uses Prototype: JSON.stringify() array bizarreness with Prototype.js

I was able to fix the problem with one of the answers: https://stackoverflow.com/a/6611126/132374

Community
  • 1
  • 1
Jon Onstott
  • 13,499
  • 16
  • 80
  • 133