I am experiencing an issue where I am in need of passing a JSON as an HTML attribute. I have the JSON string:
{"filename":"myFile.js","content":"var k = 'My Value'"}
Which I am passing to a html attribute:
<ide file-json='{"filename":"myFile.js","content":"var k = 'My Value'"}'></ide>
The issue occurs where var k = 'My Value' as the ' mark is unescaped and causing the html parser to think the value of attribute file-json is {"filename":"myFile.js","content":"var k = rather than the full string. The file-json attribute is going to be read via javascript for additional processing.
The values for both the json keys of filename and content are user generated, and can have almost any value. Is there a way escape the entire file-json attribute?
Things that I have already tried, and the reason for their failure are below: (The actual json input can be extremely large.)
Use a giant regular expression to escape any offending instances in the json file. This for two primary reasons, the first being that it was slow, but more importantly it is a "dumb" solution and often makes mistakes causing additional errors, and data corruption.
Convert the entire json structure into base64/hex; pass this encoded structure to
file-json; and then in the javascript when it is read, convert it from base64 back into a json string; and finally continue processing. This so far is the best solution that I have come up with as it is the only one that cannot cause data corruption. However it is both slow and consists of a large number of moving parts leading to issues in maintainability and expandability.
JSON.stringify(JSON.parse(data))and you'll get a normalised representation