admin管理员组

文章数量:1389952

I am getting Json string from my server as below

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.

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.

I am getting Json string from my server as below

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.

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.

Share edited Jan 13, 2014 at 3:58 xdazz 161k38 gold badges254 silver badges278 bronze badges asked Jan 13, 2014 at 3:49 Pinal DavePinal Dave 5334 gold badges14 silver badges27 bronze badges 3
  • Try var str = '{"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"}'; – Nouphal.M Commented Jan 13, 2014 at 3:54
  • Try this stackoverflow./questions/7611845/… – Myth Commented Jan 13, 2014 at 3:56
  • Never say "but it's giving error" without actually posting the error message. – Phil Commented Jan 13, 2014 at 4:04
Add a ment  | 

5 Answers 5

Reset to default 2

The str is already an object.

You could use jQuery.map method.

var str = {"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"};
var result = $.map(str, function(value, key) {
  return [[key, value]];
});

Try this map example

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 pollyfill and Array.prototype.map pollyfill

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]]);
    }
}
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];
}

Assuming you're talking about actual string that 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 string representing an array. To make a real array out of it you can do something like this:

var arr;
eval('arr = ' + str);

This is the only legitimate use of eval I can advocate.

Demo: http://jsfiddle/h8c6w/

本文标签: javascriptjquery converting json string to arrayStack Overflow