I have a string
var myString = "['Item', 'Count'],['iPad',2],['Android',1]";
I need to convert it into an array where:
myArray[0][0] = 'Item';
myArray[0][1] = 'Count';
myArray[1][0] = 'iPad';
myArray[1][1] = 2;
etc...
The string can vary in length but will always be in the format above. I have tried splitting and splicing and any other "ing" I can think of but I can't get it.
Can anyone help please?
I have a string
var myString = "['Item', 'Count'],['iPad',2],['Android',1]";
I need to convert it into an array where:
myArray[0][0] = 'Item';
myArray[0][1] = 'Count';
myArray[1][0] = 'iPad';
myArray[1][1] = 2;
etc...
The string can vary in length but will always be in the format above. I have tried splitting and splicing and any other "ing" I can think of but I can't get it.
Can anyone help please?
Share Improve this question edited Nov 29, 2012 at 16:19 dda 6,2032 gold badges27 silver badges35 bronze badges asked Nov 29, 2012 at 16:16 FredFred 5,8084 gold badges46 silver badges76 bronze badges4 Answers
Reset to default 20If the string is certain to be secure, the simplest would be to concatenat [
and ]
to the beginning and end, and then eval
it.
var arr = eval("[" + myString + "]");
If you wanted greater safety, use double quotes for your strings, and use JSON.parse()
in the same way.
var myString = '["Item", "Count"],["iPad",2],["Android",1]';
var arr = JSON.parse("[" + myString + "]");
This will limit you to supported JSON data types, but given your example string, it'll work fine.
write your code like
var myString = "[['Item', 'Count'],['iPad',2],['Android',1]]";
and just
var arr = eval(myString);
try this :
JSON.parse("[['Item', 'Count'],['iPad',2],['Android',1]]".replace(/\'/g,"\""))
I tried to use eval, but in my case it doens't work... My need is convert a string into a array of objects. This is my string (a ajax request result):
{'printjob':{'bill_id':7998,'product_ids':[23703,23704,23705]}}
when I try:
x = "{'printjob':{'bill_id':7998,'product_ids':[23703,23704,23705]}}";
eval(x);
I receive a "Unexpected token :" error.
My solution was:
x = "{'printjob':{'bill_id':7998,'product_ids':[23703,23704,23705]}}";
x = "temp = " + x + "; return temp;"
tempFunction = new Function (x);
finalArray = tempFunction();
now a have the object finalArray!
I hope to help