0

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 ?

random_user_name
  • 25,694
  • 7
  • 76
  • 115
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191
  • **why** do you want it to look like that? Javascript is forgiving on variable types, so unless you need it to be an integer (or float), what difference does it make? – random_user_name Jan 08 '16 at 19:58
  • 1
    This is a duplicate. The issue is on your PHP side. See this answer: http://stackoverflow.com/questions/1390983/php-json-encode-encoding-numbers-as-strings – random_user_name Jan 08 '16 at 20:00

4 Answers4

2

Could you just do something as simple as this?

$.each(data, function() {
    list.push([Number(this.time), Number(this.playersonline)]);
}
tlewis
  • 441
  • 3
  • 7
1

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

Community
  • 1
  • 1
MrE
  • 19,584
  • 12
  • 87
  • 105
1

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]);
})
Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
0

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

livepanzo
  • 192
  • 5