简体   繁体   中英

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-28', 6]", "['2013-03-01', 3]", ...

How can I make in JavaScript from this an array of arrays? Is this even possible? I mean, I've tried with jQuery makeArray or with parseJSON with no success. What is the most preferred method?

Edit:

function submitForm(t) {
    $.ajax({type:'GET', url: 'charts.php', data:$(page_id).serialize(), success:
        function(response) {
            var myFanRemovesData = new Array(response);
            var myChart = new JSChart(chart_id, 'line');
            myChart.setDataArray(myFanRemovesData);

I have to use the array of arrays to set myFanRemovesData with it

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)

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.

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM