12

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?

4 Answers 4

20

If 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.

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

4 Comments

@RoyiNamir: That was already noted in my answer, but I added the modified string to be clear.
Great! I've been searching for something like this for awhile! Thanks!
You need to add ; at the end ( eval("[" + myString + "];"); )
eval is dangerous, you should not use it on any content that the user can interact with in any way!
1

write your code like

var myString = "[['Item', 'Count'],['iPad',2],['Android',1]]";

and just

 var arr = eval(myString);

Comments

1

try this :

JSON.parse("[['Item', 'Count'],['iPad',2],['Android',1]]".replace(/\'/g,"\""))

enter image description here

Comments

0

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

1 Comment

new Function(string) is just as dangerous as eval, make sure that a user cannot change any attributes within the Object`.

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.