[wp-trac] [WordPress Trac] #59234: Introduce a `wp_json_decode()` function, including validation when available
WordPress Trac
noreply at wordpress.org
Thu Nov 16 17:23:00 UTC 2023
#59234: Introduce a `wp_json_decode()` function, including validation when
available
-------------------------------+---------------------
Reporter: jrf | Owner: (none)
Type: enhancement | Status: new
Priority: normal | Milestone: 6.5
Component: General | Version: 6.4
Severity: normal | Resolution:
Keywords: php83 needs-patch | Focuses:
-------------------------------+---------------------
Comment (by dalleyne):
Replying to [comment:2 jrf]:
> Happy to have a think about the function name, maybe call it
`wp_json_validate_and_decode()` ?
`wp_safe_json_decode` is a good alternative. It'll imply that it
validates, and decodes.
>
>
> > - If we were to run PHP 8.3 native `json_validate` _and_
`json_decode` inside the new `wp_json_decode`, wouldn't that be a
performance degradation for valid data?
>
> From what I read in the mailing list discussion and the RFC, the PHP
native (C) implementation is lightning fast, so that should be
unnoticeable.
>
> > - I think a more mild approach would be to polyfill `json_validate`
function? That way, we are giving the choice to the programmer if we are
dealing with potentially invalid JSON. For PHP 8.3, we don't have a
performance penalty, but at least now the choice is explicit?
>
> There was a whole discussion about the (im)possibility of polyfilling
this reliably and correctly without impacting performance on the
mailinglist and I think some of it is also mentioned in the RFC.
>
> The problem is not so much with small bits of json, but with the large
files/streams and that is exactly the case we want to harden against. A
polyfill will just not do in that case and have a heavy performance hit,
while the native C implementation does not.
How about this implementation:
{{{#!php
<?php
function wp_safe_json_decode($json, $assoc = false, $depth = 512, $options
= 0) {
// Perform validation if json_validate is available
if (function_exists('json_validate') && json_validate( $json, $depth,
$flags & JSON_INVALID_UTF8_IGNORE ) === FALSE ) {
return new WP_Error('json_validation_error', 'JSON validation
failed.');
}
// Decode the JSON string
$result = json_decode($json, $assoc, $depth, $options);
if (json_last_error() !== JSON_ERROR_NONE) {
// Return a WP_Error with the appropriate error message
return new WP_Error('json_decoding_error', 'JSON decoding failed:
' . json_last_error_msg());
}
return $result;
}
}}}
--
Ticket URL: <https://core.trac.wordpress.org/ticket/59234#comment:4>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list