javascript jquery将json字符串转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21083562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery converting json string to array
提问by Pinal Dave
I am getting Json string from my server as below
我从我的服务器获取 Json 字符串,如下所示
var str = {"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"}
I want to convert it in an array like
我想把它转换成一个数组
var str = [["12:30 PM","1:00 PM"], ["11:30 AM","12:00 PM"]];
How would I do that?
我该怎么做?
I tried to convert using jQuery.parseJSON(str)
, but it's giving error.
我尝试使用 进行转换jQuery.parseJSON(str)
,但出现错误。
I also researched a lot in stackoverflow and there seems to be many solutionfor this problem but none of the solution is working for this issue.
我也在 stackoverflow 中研究了很多,似乎有很多解决方案可以解决这个问题,但没有一个解决方案适用于这个问题。
回答by xdazz
The str
is already an object.
该str
已经是一个对象。
You could use jQuery.mapmethod.
您可以使用jQuery.map方法。
var str = {"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"};
var result = $.map(str, function(value, key) {
return [[key, value]];
});
回答by Phil
Try this map
example
试试这个map
例子
var str = {"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"};
var convert = Object.keys(str).map(function(k) {
return [k, str[k]];
});
If you need support for IE <= 8, see Object.keys pollyfilland Array.prototype.map pollyfill
如果您需要支持 IE <= 8,请参阅Object.keys pollyfill和Array.prototype.map pollyfill
回答by Sebastien
var str = '{"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"}';
object = JSON.parse(str);
var my_array = new Array();
for(var key in object ){
my_array[key] = object[key];
}
回答by N K
Can you try this.
你可以试试这个。
var p = {"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"}
var o = [];
for (k in p) {
if (p.hasOwnProperty(k)) {
o.push([k, p[k]]);
}
}
回答by Yuriy Galanter
Assuming you're talking about actual stringthat you're getting from the server, you can do a plain string replacement:
假设您正在谈论从服务器获取的实际字符串,您可以进行简单的字符串替换:
var str = '{"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"}';
str = str
.replace('{"','[["')
.replace('"}','"]]')
.replace('","','"],["')
.replace(/":"/g,'","')
This will make str
into stringrepresenting an array. To make a real array out of it you can do something like this:
这将str
变成表示数组的字符串。要从中制作一个真正的数组,您可以执行以下操作:
var arr;
eval('arr = ' + str);
This is the only legitimate use of eval
I can advocate.
这是eval
我可以提倡的唯一合法使用。