note 127556 added to function.json-decode

From: Date: Tue, 30 Aug 2022 15:05:01 +0000
Subject: note 127556 added to function.json-decode
Groups: php.notes 
Request: Send a blank email to php-notes+get-219497@lists.php.net to get a copy of this message
As of PHP 8.x, json_decode no longer supports passing NULL as the json to be decoded. If you're anything like me, you upgraded from PHP 7.x to PHP 8.x and discovered that everywhere you were using JSON in your code, there were some new deprecation warnings getting in your way. So, since I use auto_prepend_file in my php.ini, this was a super easy solution. My recommendation is to do the same thing. Create an auto_prepend_file and put this snippet in it, then add your auto_prepend_file to your php.ini <?php // the new function define("decode", "json_decode"); define("encode", "json_encode"); function json($action, $object, $pretty=false){ if($object == NULL) return NULL; if($action == decode){ return json_decode($object, true); }elseif($action == encode){ if($pretty){ return json(encode, $object, JSON_PRETTY_PRINT); }else{ return json(encode, $object); } }else{ throw new Exception("Invalid action provided to json()"); } } ?> <?php // usage $json = json(encode, ["myObject" => "is not an Object ;)"]); // {"myObject": "is not an Object ;)"} $decoded = json(decode, $json); // Array([myObject] => "is not an Object ;)") json(encode, NULL); // null, with no deprecation warning. // and finally, json(encode, $decoded, true); // Returns: // { // "myObject": "is not an Object ;)" // } ?> Note: I'm sure there is LOTS of room for improvement, such as adding support for the other options in json_encode/json_decode, this is just a baseline function for you to use in the interim if you so choose to. ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.173 (proxied: 2605:8d80:480:59f1:19f9:7d73:9d67:31ba) ---- Manual Page -- https://php.net/manual/en/function.json-decode.php Edit -- https://main.php.net/note/edit/127556 Del: integrated -- https://main.php.net/note/delete/127556/integrated Del: useless -- https://main.php.net/note/delete/127556/useless Del: bad code -- https://main.php.net/note/delete/127556/bad+code Del: spam -- https://main.php.net/note/delete/127556/spam Del: non-english -- https://main.php.net/note/delete/127556/non-english Del: in docs -- https://main.php.net/note/delete/127556/in+docs Del: other reasons-- https://main.php.net/note/delete/127556 Reject -- https://main.php.net/note/reject/127556 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#219497) next »