Decoding HTML with jQuery

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:

{"name": "John"}

turns into this:


This makes it difficult for the front-end JavaScript to turn that string back into a JSON object since 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.


Since JavaScript/jQuery does not have an existing method to do this, we can use this simple trick to decode HTML:

[javascript light=”true”]
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.