1

Here I am dynamically getting a string like this:

  var datN="{y:12 ,marker: {symbol: 'url(http://abc.com//1446/t_23718.gif)'}},72.72727,83.333336";

I want to use it in HighChart api as graph data but this is not working. I have tried and got this that if the code was like this it would work:

  var datN=[{y:12 ,marker: {symbol: 'url(http://abc.com//1446/t_23718.gif)'}},72.72727,83.333336];

so how can I convert the first variable to work like the second one? I am new to javascript please help?

UPDATE

All I want is to convert the first string to object like second one (Second one is working correctly) . I have already tries JSON.parse and eval but they didnt work. So please help?

11
  • Where do you have gotten the first variable from? Commented Jun 10, 2013 at 12:49
  • Where are you getting the string from in the first place? Commented Jun 10, 2013 at 12:49
  • duplicate of How to parse JSON in JavaScript Commented Jun 10, 2013 at 12:49
  • 3
    @NavdeepSinghBedi: Then you should make that java method output proper JSON. Can you show us its code? Commented Jun 10, 2013 at 12:58
  • 2
    Why you cannot encode array to JSON and return correct JSON object? Commented Jun 10, 2013 at 15:08

1 Answer 1

3
var datArr = JSON.parse("[" + datN + "]");

This may not work across browsers because JSON.parse is not supported by all browsers. I think you could use jquery

var datArr = $.parseJSON("[" + datN + "]");

If it still does not work, you may try

var datArr = eval("[" + datN + "]");

Although this solution is not recommended.

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

6 Comments

Eval is acceptable as long as the string is sanitized. jQuery has a regex for that.
@Quentin: an array is still a valid json object. That's not correct?? If you look carefully, this is an array with 3 items. Am I missing something?
JSON requires property names to be strings (not identifiers) and for strings to be delimited with " not '.
@Quentin True. Well, eval then, but string has to be sanitized beforehand.
@Quentin: well, so in this case, only the eval works and it is the simplest solution
|

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.