0

In my javascript code I am getting json string from cs file

var tmpString="<%=resultset2%>";    

In cs I am concatenating strings to build json string. Here is an issue the json string is returned as a string and it has " with it.

"[{id:'1',name:'Aik'},{id:'2',name:'Aik or Aik'}]"

Because of " in beginning and end javascript code treat it as a string. Kindly guide me how I should sort out this issue.

thanks

1

2 Answers 2

5
  1. Fix the JSON, it has errors (property names must be strings (and thus quoted), and only " are acceptable for quoting strings in JSON). JSON is a subset of JavaScript, you can't use all of JS' syntax in JSON. As a rule of thumb, if you are concatenating strings to produce a data format, then you are doing it wrong. http://json.org/ lists a number of C# libraries that you can use to build JSON.
  2. Use json2.js
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks @David, is it possible doing on client side ? if I try doing it on server side it will requrie a lot of work to do in changes.
If you really, really want to just hack together support for treating that string as an object instead of working with JSON … then just dump the JS object instead of making it a string: var tmpString=<%=resultset2%>;
I was about to add another answer to the effect of "why use JSON at all if you're just rendering javascript from a server page?" and I realized, he's not using JSON. He's just trying to render Javascript object syntax. There's no data transfer here, it's just server code writing javascript, so no point in using JSON and adding another layer.
There is a point in using JSON — it can be cleanly generated from mature libraries and thus reduce the risk of XSS problems generated by user data.
@jamietre. It is JSON. It's the easiest way for your server side to pass values to your client side JS. Doing it from the page itself (instead of an XHR) saves a trip to the server.
|
2

Change this:

var tmpString="<%=resultset2%>";

to:

var tmpString=<%=resultset2%>;

This isn't JSON, you're just writing javascript from a server page. The problem is you are creating invalid javascript syntax, you just need to remove the quotes.

The quotes aren't from resultset2 they are from your markup.

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.