Skip to content Skip to sidebar Skip to footer

Create Array Of Arrays From Json

I am receiving after an ajax call the following as response using in php json_encode: '['2013-02-24', 0]', '['2013-02-25', 0]', '['2013-02-26', 1]', '['2013-02-27', 6]', '['2013-02

Solution 1:

1) strip out the double-quotes ("):

var json = json.replace(/"/g, '');

2) wrap the whole thing in square brackets:

json = "[" + json + "]";

3) replace the single-quotes with double-quotes (because the singles won't parse):

json = json.replace(/'/g, '"');

4) parse the json string:

var arrays = JSON.parse(json);

Here is a working example. It will alert the first date in the first array. (note: the data is pulled from the DIV to simulate the AJAX call and to avoid me having to mess around with escaping quote characters)

Solution 2:

Try:

var response = ["['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]"];
for (var i = 0; i < response.length; i++) {
    var cleaned = response[i].replace(/'/g, "\"");
    response[i] = $.parseJSON(cleaned);
}

DEMO:http://jsfiddle.net/hu3Eu/

After this code, the response array will contain arrays, made out of the original strings.

Solution 3:

Just example.. because you haven't provide us with any code...

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" },
  dataType: 'json',
}).done(function( responde ) {
    $.each(responde, function(i, v){ 
      alert(v.0 + ' --- ' + v.1);
    });
});

If you receive and expecting json you directly can use it as array/object :) If its array you have to make a each loop so you can access each value..

Post a Comment for "Create Array Of Arrays From Json"