0

I have the following string

['Value',2],['Value2',4],['Value3',10]

I would like to convert this to javascript array. I should be able to

var tmpStrings = "['Value',2],['Value2',4],['Value3',10]";     
var arrStrings = JSON.parse("[" + tmpStrings + "]");

Unfortunately I get unexpected character errors. I thought that it might be the single quotes but escaping them doesn't change anything. Int seems to work fine, the below runs for me fine

var tmpInts = "[4,2],[5,3],[6,3]"; 
var arrInts = JSON.parse("[" + tmpInts + "]"); 
3
  • 1
    Can you show the expected result. It's not 100% clear that you want an array of arrays, though I suspect you do. Commented Jun 15, 2014 at 2:54
  • 1
    single quotes aren't valid JSON is why it is failing Commented Jun 15, 2014 at 2:58
  • You can invert it var tmpStrings = '["Value",2],["Value2",4],["Value3",10]'; Commented Jun 15, 2014 at 2:58

1 Answer 1

3

JSON will not accept '. So, you need to change that to double quotes, like this

console.log(JSON.parse("[" + tmpStrings.replace(/'/g, '"') + "]"));
# [ [ 'Value', 2 ], [ 'Value2', 4 ], [ 'Value3', 10 ] ]

We are just replacing all the ' in the string to double quotes.

Warning: This would replace ' with ", even if it appears in the middle of the string.

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.