protocolbuffers / protocolbuffers/protobuf
PHP - Inconsistent mergeFromJsonString behavior
@bshaffer is already working on this.
Since Feb 5, 2025.
- Dominant language
- C++
- Stars
- 72k
- Forks
- 16.3k
- Avg merge
- 1d 17h
- Merged PRs (30d)
- 140
Description
The PHP C extension implementation native PHP implementation have different behavior when deserializing a empty JSON object/array.
The native php implementation threats both '{}' and [] as valid inputs.
And the C extension allow only {} (I believe that is the correct behaviour)
This happens BC In php the function json_encode will encode a empty associative array as []
php -r "var_dump(json_encode(array_filter(['foo' => null])));"
string(2) "[]"
And we also get back the same php value when decoding both {} and []:
$php -r "var_dump(json_decode('[]', true, 512, JSON_BIGINT_AS_STRING));"
array(0) {
}
$ php -r "var_dump(json_decode('{}', true, 512, JSON_BIGINT_AS_STRING));"
array(0) {
}
PHP Implementation :
https://github.com/protocolbuffers/protobuf/blob/e3ac4c9342e5393e3fa974a420fc1bbc68e7397a/php/src/Google/Protobuf/Internal/Message.php#L1324
What version of protobuf and what language are you using?
Version: main
Language: php
OS: Linux
What did you do?
<?php
require_once (dirname(__DIR__) . '/vendor/autoload.php');
require_once (__DIR__ . '/test_util.php');
use Foo\TestMessage;
$message = new TestMessage();
$values = array_filter([
'true_optional_string' => null,
]);
$message->mergeFromJsonString(json_encode($values));
//$message->mergeFromJsonString('[]');
var_dump($message->hasTrueOptionalString());
#### Compile the extension
./php/tests/compile_extension.sh
# Run script
php -d display_errors=on -dextension=../ext/google/protobuf/modules/protobuf.so json_encode_test.php
What did you expect to see ?
Error parsing JSON
What did you see instead?
C extension:
Fatal error: Uncaught Exception: Error occurred during parsing: Error parsing JSON @1:0: Expected: '{'
PHP implementation:
bool(false)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.