最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert string to a multidimensional array - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

4 Answers 4

Reset to default 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.

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

发布评论

评论列表(0)

  1. 暂无评论