April 28, 2014
In many of our SharePoint modal dialogs, the back-end needs to send some JSON to the front-end when the dialog is closed. However, this JSON string gets HTML encoded so something like this:
turns into this:
jQuery.parseJSON() will complain about the string and throw errors. The string needs to be decoded before it can be parsed into a JSON object.
var decoded = jQuery('<div/>').html(value).text(); var json = jQuery.parseJSON(decoded);
A <div> element is created in memory but is never appended to the document. The innerHTML of this element is set to the HTML encoded string, and then its innerText is retrieved. The resulting string is decoded and can then be parsed into a JSON object.
Of course, this trick is useful for decoding any HTML encoded string – not just JSON.