Reputation: 6364
I have a testing server with PHP version 5.5.9, and we have a QA server with PHP version 5.6.16.
I am for the sake of this post using the same code branch on both instances (full disclosure: it's a Laravel install but I'm not sure this is a Laravel issue)
On the QA server, an API returns JSON with the integers unquoted as follows (this is simplified):
{["id":1,"name":"John"],["id":2,"name":"Sam"]}
But on my server (the 5.6.16 one), the same exact API call returns:
{["id":"1","name":"John"],["id":"2","name":"Sam"]}
And, Angular is not liking that and does not parse it.
The data and tables the data is coming from are exactly alike in structure - I have verified this.
Though in theory Angular should handle this(?), I don't want to touch our coding for the front end.
Regardless of what Angular is doing, the obvious solution is to have the outputs be exactly equal.
json_encode
calls in the codebase.Upvotes: 1
Views: 114
Reputation: 2037
As @RiggsFolly it definitely depends on how the source is providing the integer data. If the numbers are quoted from source, json_decoder treats them as a string.
Something you can try: json_encode as a 2nd parameter called $options. Set it to attempt to encode numbers as integers rather than strings.
http://php.net/manual/en/function.json-encode.php
PHP json_encode encoding numbers as strings
Upvotes: 0
Reputation: 94682
Its not an issue in json_encode()
it is what you are encoding that makes a difference. See this simple example
$a = array(
'id' => 111,
'astring' => 'test',
'OhLookItsANumberRecordedAsAString' => '456'
);
$json = json_encode($a);
echo $json;
Result
{"id":111,
"astring":"test",
"OhLookItsANumberRecordedAsAString":"456"
}
But if you make sure the integers are integers all is as you expect
$a = array(
'id' => 111,
'astring' => 'test',
'OhLookItsANumberRecordedAsAString' => '456',
'ANumber' => (int)'456'
);
$json = json_encode($a);
echo $json;
Result
{"id":111,
"astring":"test",
"OhLookItsANumberRecordedAsAString":"456",
"ANumber":456
}
Upvotes: 1