2

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;"} ?

1 Answer 1

1

I use &amp; for &

Try this code.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.