简体   繁体   English

PHP json_decode将有问题的值强制转换为字符串而不是float?

[英]PHP json_decode casting a problematic value to string instead of float?

I have an array of JSON data that i'd like to import. 我有一个要导入的JSON数据数组。 An example of what i'd call non-problematic JSON data would be: 我称之为非问题JSON数据的示例是:

[{
  "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. 在101546e3 = 101546x10 ^ 3的地方,这是我在json_decode的默认行为上遇到的问题,因为它将这些值强制转换为float并在其中将e3转换为000,或将e5转换为00000,因此对于上面的第一个值,我会找回1011546000、1075864000、1132356000。我无法确定此值已被修改,因为它可能是有效值。

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? 假设它可能包含字符串e ,那么我如何才能从此JSON数据中检索正确的值(通过json_decode通过JSON_decode运行之前存在于JSON字符串中)?

You have to pass JSON_NUMERIC_CHECK as second parameter in json_encode() function 您必须将JSON_NUMERIC_CHECK作为第二个参数传递JSON_NUMERIC_CHECK json_encode()函数

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 请参阅PHP Doc以获取第二个参数的各种选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM