Our PHP API outputs results using json_encode with JSON_NUMERIC_CHECK enabled, which is important for financial figures, binary values etc.. but we have recently introduced
You can try this:
{
"is_bool": 1,
"total_amount": 431.65,
"phone_number": "xn#0272561313"
}
as example in mysql: SELECT CONCAT('xn#', phone_number) as phone_number...
If you used json_encode()
, replace the string like this:
echo str_replace('xn#','',$your_encoded_json);
For what it's worth, I had a similar problem in that I have international phone numbers starting with a +
symbol. I used urlencode
on my phone number string to over come the issue:
$phone = urlencode( $phone );
pass the data to this function to get JSON encoding with + and 0 preceded data staying as a string. I am using double encoding and str_replace to get over the issue.
public static function json_encode($data){
$numeric = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
$nonnumeric = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
preg_match_all("/\"[0\+]+(\d+)\"/",$nonnumeric, $vars);
foreach($vars[0] as $k => $v){
$numeric = preg_replace("/\:\s*{$vars[1][$k]},/",": {$v},",$numeric);
}
return $numeric;
}
Instead of typecasting it to a string do something like this:
$output = array(
'is_bool' => 1,
'total_amount' => '431.65',
'phone_number' => '"0272561313"' // add quotations
);
echo '<pre>';
echo json_encode($output,JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
It'l keep the trailing zero:
{
"is_bool": 1,
"total_amount": 431.65,
"phone_number": "\"0272561313\""
}
Decode:
$test = json_encode($output,JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
$test = json_decode($test, true);
print_r($test);
Output:
Array
(
[is_bool] => 1
[total_amount] => 431.65
[phone_number] => "0272561313"
)
You no need to use
JSON_NUMERIC_CHECK
Instead use attribute-casting
https://laravel.com/docs/5.1/eloquent-mutators#attribute-casting
class SomeModel extends Model
{
protected $casts = [
'field_name' => 'array',
'status' => 'boolean'
];
}
works for me :
// $DATAS -> datas returned by the server
$DATAS = array(
array('tel' => '0606060606'),
array('tel' => '0707070707')
);
foreach($DATAS as $k => $v){
$tel = " ".$v['tel']." "; // ADD WHITE SPACE
$DATAS[$k]['tel'] = $tel;
}
echo json_encode($DATAS, JSON_NUMERIC_CHECK);
// output : [{"tel":" 0606060606 "},{"tel":" 0707070707 "}]
Maybe define css white space or trim datas in the json encoded for obtain the perfect parsed number