简体   繁体   中英

How to cast JSON array values as integers in javascript (from php / mysql)

I have a php page which gets some data in mysql database and return a json file, and then I call this json file with an ajax call :

$.ajax({
        type: "POST",
        dataType: "json",
        url: "get_players_stats.php", //Relative or absolute path to players_stats file
        success: function(data) {
            var list = [];
            $.each(data, function() {
                list.push([this.time, this.playersonline]);
            })
            console.log(list);

        }
    });

the console.log(list); shows me this :

[["-1009843200000", "1"], ["-252460800000", "2"], ["-94694400000", "3"], ["31536000000", "2"],....

but instead I want it to look like this :

[[-1009843200000, 1], [-252460800000, 2], [-94694400000, 3], [31536000000, 2],....

How can I do that ?

Could you just do something as simple as this?

$.each(data, function() {
    list.push([Number(this.time), Number(this.playersonline)]);
}

This is a type conversion problem : your data is showing as text format and you want it as number format.

You could parse the text as float in javascript, but that would likely be very inefficient, when instead you could cast the data as the type you need in the SQL query that returns the JSON.

To get you more details on how, it would be good to see how you pull the data into the JSON in the first place.

EDIT:

the actual answer you should be using is here: PHP json_encode encoding numbers as strings

Do you really need to convert those values to numeric ones? JavaScript only supports 53 bit integers, so parseInt('10765432100123456789') will be converted to 10765432100123458000 integer.

Working with large integers in JavaScript .

If you still would like to convert the response you can do something like this:

$.each(data, function() {
  list.push([+this.time, +this.playersonline]);
})

ES6 syntax http://jsbin.com/qamoru/edit?js,console

 let arr=[["-1009843200000", "1"], ["-252460800000", "2"], ["-94694400000", "3"], ["31536000000", "2"]]; let newArr = arr.map((item)=> item.map((it)=> Number(it))); console.log(newArr) 

JS Bin on jsbin.com

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