简体   繁体   中英

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?

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.

try this :

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

在此输入图像描述

write your code like

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

and just

 var arr = eval(myString);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM