0

I am rendering string javascript variable init statements at server side (using ASP MVC, but I do not think it matters) The string variable content is a valid JSON at server side, and encoded when rendered to html. My rendered statement looks like this:

 var myvariable = '{"prefix":"","name":"Grid&...

Quatation marks and other special chars in the string were encoded to html entities, which is completely OK, unless this encoding the variable declaration would by syntactically incorrect.

However I must get back the original string content at client side which was a correct JSON at server side. How can I accomplish this with javascript or jQuery? (Please note, then I do know how to get a javascript object from JSON, I am not asking for that)

2 Answers 2

1

How about?

var myjsonobject = JSON.parse(decodeHtml(myvariable));
function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
   return txt.value;
}

Note that it's not tested

EDIT: Tested it https://jsfiddle.net/Lmz20s5z/

EDIT2: *See the console log for results

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

Comments

0

On server side you can escape quotation marks with a backspace \" then you can just do JSON.parse(string) on that string clientside.

JSON.parse('{\"prefix\":\"\",\"name\":\"Grid\"}');

1 Comment

Not only quotation marks are there, but script parts also. I do not want to reinvent the wheel, ASP MVC have server side infrastructure to render a correct html string by escaping all specials with html entities. Now I am looking for the inverse transformation in javascript or jQuery

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.