Search code examples
javascriptjsonhtml-encode

HTML decoding issue with quotes


I have an input hidden element, the value of which contains JSON of an HTML encoded string. Something like

{"QuestionInstruction":"<snippet lang="java"> public class Test() {\n\n}</snippet>","QuestionDescription":"it this correct?","Choices":["True","False"] }

and when I do

var text = document.getElementById('inputId').value, 

the &quot automatically gets converted to "". The value of text comes as -

{"QuestionInstruction":"<snippet lang="java"> public class Test() {\n\n}</snippet>","QuestionDescription":"it this correct?","Choices":["True","False"] }

So, then JSON parsing fails. :(

I am using FF9.


Solution

  • I have managed to get around this by using the following function if I know to expect a value that could contain quotes when creating a JSON string/object...

    function getJSONFriendlyString(text) {
        return text.replace(/"/g, "\\\"");
    }
    

    Hope that helps you