'Calling JSON.parse on php returned array, some numbers parsed as INT, others parsed as STRING

Looking for an explanation rather than an answer here :)
I have this php script that is called with jquery's AJAX

$query = 'SELECT MONTH(PRSD#) as "Monat", CAST(AVG(GASVBR) as DECIMAL(10,3)) as "Gas", CAST(AVG(OLVBR) as DECIMAL(10, 3)) as "Öl", CAST(AVG(STROVBR) as DECIMAL(10,3)) as "Strom" FROM swind.gwenergy GROUP BY YEAR(PRSD#), MONTH(PRSD#) ORDER BY MONTH(PRSD#)';
    
    $dbReturn = $database->execute($query, array());
    
    $jsonArray = array();
    
    while ($row = db2_fetch_assoc($dbReturn)) {´
        echo json_encode($jsonArray);
    }

When I call in the JS side of things:

let parsedData = JSON.parse(jsonData);
I am returned with this:
{Monat: 2, Gas: '13750.607', Öl: '1447.432', Strom: '3901.051'}
How come the Monat value is not in quotes?
I thought that maybe because the $query in the php script was returning DECIMAL(10,3) but when I replace it with FLOOR(... the JSON.parse still wrapped the value in quotes.
Is this related to the $query response, or is this a JSON.parse action?
Look forward to hearing other ideas :) Thanks! -Boogabooga



Solution 1:[1]

I've faced a similar problem. You can check the data type on PHP with gettype()

Note that since PHP 5.3.3, there is a flag for auto-convert numerical numbers when using json_encode.

echo json_encode( $jsonArray, JSON_NUMERIC_CHECK );

This should do the work for you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 toffler