2
votes

I have data which includes inch and foot marks (\" and \'), with the response from an AJAX call returning valid JSON (the \" is escaped, and ' is not) which I am using in a HTML form.

with the following JSON response: (other items may have multiple price/size combos hence the list; this example for brevity)

{"pl":{"common":"","price":[219],"size":["2\""]}}

Note the size of 2 inches has the properly JSON escaped \".

With the following javascript (using jQuery .getJSON) the returned data does not include the escaped char:

$.getJSON(url,
    {data},
    function(json){
        var obj = json.pl.size;
        var options = '<option value="">Size</option>';
        for (var i = 0; i < obj.length; i++) {
        // possible for size to have \' and/or \" chars
            options += '<option value="' + obj[i] + '">' + obj[i] + '</option>';
        }
    // populate the select box with the options
});

The success function return:

json: Object
    pl: Object
        common: ""
        price: Array[1]
        size: Array[1]
            0: "2""

Note the size[0] data no longer has the escaped "

Question 1. Why is the JSON escaped data not respected in the success response?

And for giggles:

  1. what is the best way to escape this data in the HTML form.
1

1 Answers

1
votes

In JavaScript, here is how it is evaluated:

  • String("2\"") returns "2""
  • String("2\\\"") returns "2\""
  • String("2\\") returns "2\"

JSON requires that backslashes be escaped, so the proper syntax would be "2\\\\\\\""