I can't count how many times I've been bitten by this. From the infamous fractal blog:
"Parts of PHP are practically designed to produce buggy code. json_decode returns null for invalid input, even though null is also a perfectly valid object for JSON to decode to—this function is completely unreliable unless you also call json_last_error every time you use it." Most functions in PHP return false as an indicator for an invalid call. json_decode() returns null -- changing this to return false is also a breaking change that may not survive a vote. Because of the unreliability I don't use this function and always rely on 3rd party JSON libraries instead. On Fri, Jul 28, 2017 at 12:59 AM, Niklas Keller <m...@kelunik.com> wrote: > 2017-07-28 8:56 GMT+02:00 Giovanni Giacobbi <giova...@giacobbi.net>: > > > On 27 July 2017 at 18:00, Craig Duncan <p...@duncanc.co.uk> wrote: > > > >> On 27 July 2017 at 16:57, Niklas Keller <m...@kelunik.com> wrote: > >> > >> > It should rather just throw exceptions. Warnings do not really allow > >> error > >> > handling, they just allow error reporting. > >> > > >> > > >> Agreed, but I can't see Exceptions passing the vote. Warnings can be > >> silenced by those that don't care and converted to Exceptions by those > >> that > >> do > >> > > > > Error management is a painful topic in PHP, expecially when considering > to > > the way fopen() behaves, where you *need* to use the "@" suppression if > > you want it to behave the way you expect it to behave. > > > > About Exceptions you can easily build a framework around core functions, > > for example this is in my core library for all projects: > > > > ```php > > function safe_json_decode($json = null) { > > if ($json == "") > > return null; > > > > $retval = json_decode($json, true, 512, JSON_BIGINT_AS_STRING); > > if (json_last_error() != JSON_ERROR_NONE) > > throw new JsonDecodeException(json_last_error_msg(), > > json_last_error()); > > > > return $retval; > > } > > ``` > > > > So yes, the behaviour of json_decode() might not be optimal, but it's > fine > > the way it is. > > > > Yes, I know. There's https://github.com/DaveRandom/ExceptionalJSON. > > While the current API works, I'm not sure whether I'd say its fine. > > Regards, Niklas >