Fred
Fred

Reputation: 5808

Convert string to a multidimensional array

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?

Upvotes: 12

Views: 22799

Answers (4)

Bocapio
Bocapio

Reputation: 109

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

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148524

try this :

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

enter image description here

Upvotes: 1

Yogesh Prajapati
Yogesh Prajapati

Reputation: 4870

write your code like

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

and just

 var arr = eval(myString);

Upvotes: 1

I Hate Lazy
I Hate Lazy

Reputation: 48761

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.

Upvotes: 20

Related Questions