Answer the question
In order to leave comments, you need to log in
json_encode - strong typing
Hello,
has anyone come across this problem. I am making an api for an old project for use on android / iphone, and for them it is important that int be given as int, not a string, float as float, and so on. (not "key":"23.2", but "key":23.2). This is solved via JSON_NUMERIC_CHECK in json_encode, or regular expression if php < 5.3. But now I have a problem with the fact that if I have a string-number in those values where there should be pure strings, then it is also translated into a number. For example, there is a title or filter key, where the values must be strings:
- "filter":"12 mm" remains a string
- but "filter":"12" -->> becomes "filter":12 although I need a pure string here
I have one solution, this is to do post-processing after json_encode and replace strings where they should be through preg_replace, but it seems to me that this is not a very good idea ...
In general, can you tell me something? =)
Thank you.
*In general, the correct answer is to watch the types before passing the array to json_encode and not use JSON_NUMERIC_CHECK. If the data is selected from the database, then manually convert the type for the necessary keys to numeric (intval, floatval)
Answer the question
In order to leave comments, you need to log in
Do not post-processing, but pre-processing. Those. we run through the array and where we need numbers we do an explicit cast to the desired types.
You know, I tried a bunch of combinations, I thought maybe the problem was nesting and I couldn’t repeat so that the number was encoded into a string ...
In theory, I even understood what was the matter ...
In some places I did this
$sql = "select ...";
$result_raw = query($sql);
$api_response = array(
"id" => $result_raw["id"],
"filter" => $result_raw["db_filter"]
//...
);
json_encode($api_response);
$api_response = array(
"id" => intval($result_raw["id"]),
"filter" => $result_raw["db_filter"]
//...
);
{
"id": 234, // instead of "id": "234"
"filter": "12" // instead of "filter": "12" with JSON_NUMERIC_CHECK
}
I would do this:
enter an array with the types of variables that must be explicitly specified in json.
and applied these types. Something like this, in pseudocode.
class MyJson {
private $types = ['id'=>intval,'name'=>'strval','price'=>'floatval'];
public function convert2Json($array)
{
foreach ($array as $key=>$value)
{
if (isset( $this->types[$key] )) $array[$key] = {$this->types[$key]}($value);
}
return json_encode($array);
}
}
And if so?
$array = array('a' => 1, 'b' => '3', 'c' => '3.14');
$json = json_encode($array);
$json = preg_replace('/\"(\d+([\.\,]\d+)?)\"/isu', '$1', $json);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question