Passing json string from axpx.cs to aspx facing quotes problem

Please kindly help me with this question. I’ve seen a question similar to mine, but it’s closed and I didn’t found the proper answer in it. See: Passing list of string values from aspx.cs to aspx

I got a json string which contains user’s input in aspx.cs, and I want to pass that json string to aspx.

The code in aspx.cs is like below:

protected string GetUserData() {     // just some mock data     Dictionary<string,string> userData = new Dictionary<string,string>();     // question comes from double quotes and single quotes     userData.Add("mock", "I\'m fine\"");     return JsonConvert.SerializeObject(userData); } 

And the aspx code is like below:

<script type="text/javascript">     window.userData = {         cache: <%= GetUserData() %>     }; </script> 

This code works fine. But the format of window.userData.cache is Object instead of string. When I show it in console, it prints {mock: "I'm fine""}. It seems that asp.net have discarded the escape character and the outermost pair of double quotes for me. That’s the key problem.

For some reason, I have to compare the origin variable assignment method with JSON.parse method in JavaScript. That means that I need the json string in origin format in aspx. I tried to modify my code in aspx to solve it with below codes.

cache: JSON.parse('<%= GetUserData() %>') 

The problem is that window.userData.cache is JSON.parse('{"mock": "I\'m fine\""') now. The single quotes before { and m make a pair.

Here is the error message in Chrome:

Uncaught SyntaxError: Unexpected token ' in JSON at position xxxxx 

I would appreciate it if you could kindly give me any idea. Thanks.

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.