WCF icon indicating copy to clipboard operation
WCF copied to clipboard

Use `JsonException` when decoding / encoding JSON

Open dtdesign opened this issue 1 month ago • 0 comments

We cannot change the behavior of the existing JSON::encode() and JSON::decode() implementations but we can deprecate them in favor of new methods that offer the same but rely on \JSON_THROW_ON_ERROR.

/**
 * @throws \JsonException
 */
public static function stringify(mixed $value): string
{
    return \json_encode($value, \JSON_THROW_ON_ERROR);
}

/**
 * @throws \JsonException
 */
public static function parse(string $json): mixed
{
    return \json_decode($json, true, flags: \JSON_THROW_ON_ERROR);
}

The naming is taken from the JSON class in JavaScript and allows us to transition to the new helper functions while being fully backwards compatible.

The functions are also much simpler by not allowing to toggle any of the behavior. The rationale behind that is simple: These are merely convenient wrappers and using a direct call to \json_encode() or \json_decode() is a drop-in replacement for these helper functions due to the ability to use the same exceptions.

dtdesign avatar Nov 24 '25 14:11 dtdesign