I have receive a string with this format
"{'key': value}, {'key': value},{'key': value} ..."
I need to convert this string to javascript array to use like this:
var $arrayValue = [{'key': value}, {'key': value},{'key': value}];
how to conver this string into array?
Dan Hlavenka
3,8308 gold badges44 silver badges63 bronze badges
asked Sep 30, 2013 at 4:58
xzegga
3,1693 gold badges29 silver badges47 bronze badges
1 Answer 1
string = string = '{"key": "value"}, {"key": "value"}'
JSON.parse("[" + string + "]")
answered Sep 30, 2013 at 5:01
Ryan Bigg
108k25 gold badges243 silver badges264 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Dan Hlavenka
Assuming you can be sure each object is valid JSON, this is the best way to do it.
xzegga
The console get me this error: Uncaught SyntaxError: Unexpected token '
Ryan Bigg
This is because you're passing in single quoted JSON keys/values. Use double quotes.
xzegga
This string is a variable extracted from json query, this is automatically extracted with string double quotes "{'key': value}", if i replace the single quote with double this string fail: string = string = "{"key": "value"}, {"key": "value"}" notice the double quotes before and after string :S
xzegga
Instead your example code, I have this: string = string = myVariable; JSON.parse("[" + string + "]") This variable is automatically placed with double quotes "",
lang-js