[wp-trac] [WordPress Trac] #59234: Introduce a `wp_json_decode()` function, including validation when available

WordPress Trac noreply at wordpress.org
Tue Aug 29 11:44:35 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.4
Component:  General            |     Version:  trunk
 Severity:  normal             |  Resolution:
 Keywords:  php83 needs-patch  |     Focuses:
-------------------------------+---------------------

Comment (by jrf):

 @ayeshrajans

 Replying to [comment:1 ayeshrajans]:
 > Thanks for opening this ticket. I have a few thoughts on this:
 >
 >  - If we were to introduce a `wp_json_decode` function (which I actually
 did, that lead me to these points), we will have to throw an exception to
 handle errors. This is because `false` itself is a valid return value, now
 we are overstepping the general use case of "decode" to "validate and
 decode".

 I imagine a `WP_Error` object could work as a "invalid" return value and
 be the only exception to what can be reliably decoded by the function ?

 Having said that, I'd be happy for WP to start using Exceptions, though I
 suspect that needs a separate discussion.

 Happy to have a think about the function name, maybe call it
 `wp_json_validate_and_decode()` ?
 I do still think a function is better than having the duplicate code all
 over the place with a larger risk of people forgetting to validate.


 >  - 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.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/59234#comment:2>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list