I have a JSON object that may include invalid XML characters, for example:
{
items: [
{ id: 1, description: 'hello <b>world</b>­' }
]
}
These values are inputted into a textarea by the user, typically through copying and pasting. Due to legacy reasons, I bind properties like description
to XML and then later parse the XML on the server.
It is crucial to ensure that the XML generated from the JSON data is valid, which means we need to escape the values in the JSON. If left unescaped, it would result in invalid XML like this:
<data>
<myItems>
<item id="1">hello <b>world</b>­</item>
</myItems>
</data>
What is the best way to escape the JSON content to ensure it produces only valid XML?
Requirement: The function escape(json)
should produce the same output as escape(escape(json))