diff --git a/src/Utils/Json.php b/src/Utils/Json.php index 2b4f12570..84d72f666 100644 --- a/src/Utils/Json.php +++ b/src/Utils/Json.php @@ -23,15 +23,17 @@ final class Json const PRETTY = 0b0010; + const FORCE_OBJECT = 0b10000; /** - * Returns the JSON representation of a value. Accepts flag Json::PRETTY. + * Returns the JSON representation of a value. Accepts flag Json::PRETTY and JSON::FORCE_OBJECT. */ public static function encode($value, int $flags = 0): string { $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | ($flags & self::PRETTY ? JSON_PRETTY_PRINT : 0) - | (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7 + | ($flags & self::FORCE_OBJECT ? JSON_FORCE_OBJECT : 0) + | (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7 $json = json_encode($value, $flags); if ($error = json_last_error()) { diff --git a/tests/Utils/Json.encode().phpt b/tests/Utils/Json.encode().phpt index ba84bbfd1..2192d2092 100644 --- a/tests/Utils/Json.encode().phpt +++ b/tests/Utils/Json.encode().phpt @@ -35,6 +35,7 @@ Assert::same('"\u2028\u2029"', Json::encode("\u{2028}\u{2029}")); // JSON_PRETTY_PRINT Assert::same("[\n 1,\n 2,\n 3\n]", Json::encode([1, 2, 3], Json::PRETTY)); +Assert::same("{}", JSON::encode([], Json::FORCE_OBJECT)); Assert::exception(function () { Json::encode(NAN);