Reputation: 7677
I have an array of JSON data that i'd like to import. An example of what i'd call non-problematic JSON data would be:
[{
"records": [{
"timestamp": 1437805800,
"Import": 1011546
},{
"timestamp": 1437805800,
"Import": 1075864
},{
"timestamp": 1437805800,
"Import": 1132356
}]
}]
The problem that I am having though is that sometimes the data might be like this:
[{
"records": [{
"timestamp": 1437805800,
"Import": 1011546e3
},{
"timestamp": 1437805800,
"Import": 1075864e3
},{
"timestamp": 1437805800,
"Import": 1132356e3
}]
}]
Where 101546e3 = 101546x10^3 and this is where I am having issues as the default behavior of json_decode because it will cast these values to float and within that, it converts e3
as 000, or e5
as 00000 so for the first values above I would get back 1011546000, 1075864000, 1132356000. I can't tell that this value had been modified as it may be a valid value.
How am I able to retrieve the correct value (present within the JSON string before running it through json_decode) from this JSON data given that it may contain the string e
within what should be an integer value?
Upvotes: 0
Views: 683
Reputation: 8496
You have to pass JSON_NUMERIC_CHECK
as second parameter in json_encode()
function
For example
$numbers = array('+123123', '-123123', '1.2e3', '0.00001');
var_dump(
$numbers,
json_encode($numbers, JSON_NUMERIC_CHECK)
);
echo "Strings containing improperly formatted numbers".PHP_EOL;
$strings = array('+a33123456789', 'a123');
Refer PHP Doc for second parameter various option
Upvotes: 2