2

My form in the html DOM is a checkbox to click (there can be more than one). The problem occurs in the description string when ever I use an apostrophe, since my list object is single-quote deliniated. This is one of the checkboxes in the form:

<input type="checkbox" id="cbx" name="cbx" value="{'getPic': 'url', 'picsrc': 'http://lh3.ggpht.com/_ZB3cttqooN0/SVmJPfusGWI/AAAAAAAADvA/GuIRgh6eMOI/Grand%20Canyon%201213_121508214.JPG', 'pos': None, 'description': 'Here's what it REALLY looks like at 5:30am! Bring your headlight!'}">

The javascript that reads the values of the checked checkboxes and pushes them into an array (list):

var pylist = [];
 for (i=0; i<document.picList.cbx.length; i++) {
 if (document.picList.cbx[i].checked) {
 pylist.push( document.picList.cbx[i].value );
 }
 }
var getstr = JSON.stringify(pylist);

The problem is always that getstr at this point has chopped off everthing after the single quote in the description property. I've tried different ways of escaping it to little avail.

Nosredna
86.8k16 gold badges98 silver badges124 bronze badges
asked Jun 7, 2009 at 17:50
1
  • For reference, this isn't valid JSON. The strings need to be double-quoted, and any decently compliant JSON serializer will do so. Commented Jan 20, 2012 at 6:07

2 Answers 2

1

The problem is that the value of the checkbox already is a JSON string. One solution would be to call JSON.parse() on the value:

var pylist = [];
 for (i=0; i<document.picList.cbx.length; i++) {
 if (document.picList.cbx[i].checked) {
 pylist.push( JSON.parse( document.picList.cbx[i].value) );
 }
 }
var getstr = JSON.stringify(pylist);
answered Jun 7, 2009 at 17:54
Sign up to request clarification or add additional context in comments.

Comments

0

I've run into the same issue - we stick json in a hidden field so we don't have to query the server on every page. We replace apostrophes with a "code" before putting into the html - we added a javascript function that replaces the code with an apostrophe.

Really hacky, but it works really well. Of course, we have one place in the code that gets json from the server and one place where javascript needs to parse it - if you find you're repeating the methods throughout your code, your mileage will vary.

answered Jun 7, 2009 at 17:57

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.