Dan
Dan

Reputation: 9468

Append valid json to html element

I am trying to dynamically insert a valid json array into html, but I am running into an issue when the text has a quote, apostrophe, or other character that should be escaped. Here is an example to demonstrate the issue - let's say this is the HTML:

<p>text</p>

Then I want to dynamically generate JSON like so:

var x = '"in quotes"';
$( "p" ).after( '{"0":"' + x + '"}');

If var x were a value without any characters that need to be escaped the appended text would be valid JSON, but in this case there are quotes in the text being used.

The same result is achieved if using &quot; instead of "

var x = '&quot;in quotes&quot;';
$( "p" ).after( '{&quot;0&quot;:&quot;' + x + '&quot;}');

Here is a json fiddle with both examples

Is there a way to achieve the desired result which would look like this: {"0":"&quot;in quotes&quot;"} ?

Upvotes: 2

Views: 64

Answers (1)

Tushar Acharekar
Tushar Acharekar

Reputation: 900

I use &amp; for &

Try this code.

var x = '&amp;quot;in quotes&amp;quot;'; $( "p" ).after( '{&quot;0&quot;:&quot;' + x + '&quot;}');

Upvotes: 1

Related Questions