1

I am parsing a JSON object and displaying the data into a table. However, some of this data has brackets like this < , > , >= , <= followed by either a letter or a number. In this case, the data from JSOn looks like this:

    (rRandomString<iamNotaTAG)

and the resulting html after appending it is this:

    (rRandomString
    <iamNotaTAG) td="" <=""></<iamNotaTAG)>

Update 1: The code I am using to parse the JSON is this

    var json = $.parseJSON(data);
    for (var i = 0, maxlength = json.length; i < maxlength; i += 1 ) {
       my_string = json[i][1];
       result += "<tr class='my_result'>"
              + "<td>"+my_string+"</td></tr>"
    }
    $('#my_table tbody').html(result);
murielg
  • 644
  • 2
  • 7
  • 15

2 Answers2

3

What you should really do is add the content as text rather than as HTML. This is a bit tricky for you, as you are appending an HTML structure. So it needs a bit of a rethink:

var result = $([]); // empty object

var json = $.parseJSON(data);
for (var i = 0, maxlength = json.length; i < maxlength; i += 1 ) {
   var my_string = json[i][1]; // this should really be locally defined, I think

   var newcontent = $('<td>')      // create a td element
       .text(my_string)            // add the content as text
       .wrap('<tr>')               // wrap the td in a new tr
       .parent()                   // go up to the tr
           .addClass('my_result'); // add the class to the tr

   result.add(newcontent);         // add the tr to the set of trs
}
$('#my_table tbody').html(result); // add all the trs to the tbody
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
2

Simply escape strings before adding them to resulting html (http://jsfiddle.net/cvAuB/)

var json = [[0, "some str"], [1, "some <str>"], [0, "some str &&& <a>not a link</a>"]], },           result = "", current;


var tagsToReplace = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;'
}

function replaceTag(tag) {
    return tagsToReplace[tag] || tag;
}

function textify(str) {
    return str.replace(/[&<>]/g, replaceTag);
};
for (var i = 0, maxlength = json.length; i < maxlength; i++ ) {
   current = textify(json[i][1]);
   result += "<tr class='my_result'>"
          + "<td>"+current+"</td></tr>"
}

$('#my_table tbody').html(result);
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • Thank you. This is the easiest way for me to solve this problem. In the long run, I will be changing how I get this done, considering an approach more like @lonesomeday 's answer. But for right now, this is just what I needed. – murielg Jul 03 '13 at 18:38
  • You are welcome. I do recommend to check if the resulting performance is suitable for you before adding moar jquery awesomeness to your production code. :) – Yury Tarabanko Jul 03 '13 at 18:45