Pinal Dave
Pinal Dave

Reputation: 533

jquery converting json string to array

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.

Upvotes: 1

Views: 12442

Answers (5)

Sebastien
Sebastien

Reputation: 250

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

Upvotes: 0

N K
N K

Reputation: 3337

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

Upvotes: 0

Yuriy Galanter
Yuriy Galanter

Reputation: 39807

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.net/h8c6w/

Upvotes: -1

xdazz
xdazz

Reputation: 160953

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

Upvotes: 2

Phil
Phil

Reputation: 165059

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

Upvotes: 1

Related Questions