简体   繁体   中英

Convert JSON into JavaScript array

I get response from server:

{'data':['29/10/2009','13/04/2009','19/10/2009','07/04/2009','20/05/2009','27/02/2010',
'20/04/2009','16/06/2009','15/12/2009','22/06/2009','21/09/2009','28/07/2009',
'19/01/2009','14/05/2010','30/03/2009','06/04/2009','21/01/2010','10/03/2009',
'17/09/2009','09/04/2009','27/10/2009'.....]}

I want to get this date array and put it into JS array:

                success: function(response){    
                intObj = response.responseText;
                for(var i in intObj) {
                    console.log(i);
                    if(intObj.hasOwnProperty(i) /*&& !isNaN(+i)*/) {

                        dateArray[+i] = intObj[i];
                    }
                }
            }

But get result in my array:

["\r", "\n", "\r", "\n", "\r", "\n", "\r", "\n", "\r", "\n", "\r", "\n", "\r", "\n",
"\r", "\n", "\r", "\n", "\r", "\n", "{", "'", "d", "a", "t", "a", "'", ":", "[", "'", 
"2", "9", "/", "1", "0", "/", "2", "0", "0", "9", "'", ",", "'", "1", "3", "/", "0", 
"4", "/", "2", "0", "0", "9", "'", ",", "'", "1", "9", "/", "1", "0", "/", "2", "0", 
"0", "9", "'", ",", "'", "0", "7", "/", "0", "4", "/", "2", "0", "0", "9"...]

How to put into array only dates? Like this '29/10/2009','13/04/2009','19/10/2009','07/04/2009'] .

You need to parse the string as JSON:

var result = JSON.parse(response.responseText);

You can then get the array directly:

var array = result.data;

You have to use JSON.parse() . I believe you need to use the responseText property , which returns the response as a string.

var jsonObject = JSON.parse(response.responseText);
var dataArray = jsonObject.data;

Response is an object

var array = response.data;

Reponse is a string

Convert it to object:

var response = JSON.parse(response);

您必须解析结果。

var arrayOfDates = JSON.parse(response.responseText).data;

try to use

var intObj = eval("(" + response + ");");
for (var i in intObj.data) {
        console.log(i);
        if(intObj.hasOwnProperty(i) /*&& !isNaN(+i)*/) {
             dateArray[+i] = intObj[i];
        }
}

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