note 111551 modified in function.json-decode by danbrown

From: Date: Mon, 04 Mar 2013 17:40:37 +0000
Subject: note 111551 modified in function.json-decode by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-193803@lists.php.net to get a copy of this message
Sometime, i need to allow comments in json file. So i wrote a small func to clean comments in a json string before decoding it: <?php /** * Clean comments of json content and decode it with json_decode(). * Work like the original php json_decode() function with the same params * * @param string $json The json string being decoded * @param bool $assoc When TRUE, returned objects will be converted into associative arrays. * @param integer $depth User specified recursion depth. (>=5.3) * @param integer $options Bitmask of JSON decode options. (>=5.4) * @return string */ function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) { // search and remove comments like /* */ and // $json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t](//).*)#", '', $json); if(version_compare(phpversion(), '5.4.0', '>=')) { $json = json_decode($json, $assoc, $depth, $options); } elseif(version_compare(phpversion(), '5.3.0', '>=')) { $json = json_decode($json, $assoc, $depth); } else { $json = json_decode($json, $assoc); } return $json; } ?> --was-- Sometime, i need to allow comments in json file. So i wrote a small func to clean comments in a json string before decoding it: <?php /** * Clean comments of json content and decode it with json_decode(). * Work like the original php json_decode() function with the same params * * @param string $json The json string being decoded * @param bool $assoc When TRUE, returned objects will be converted into associative arrays. * @param integer $depth User specified recursion depth. (>=5.3) * @param integer $options Bitmask of JSON decode options. (>=5.4) * @return string */ function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) { // search and remove comments like /* */ and // $json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t](//).*)#", '', $json); if(version_compare(phpversion(), '5.4.0', '>=')) { $json = json_decode($json, $assoc, $depth, $options); } elseif(version_compare(phpversion(), '5.3.0', '>=')) { $json = json_decode($json, $assoc, $depth); } else { $json = json_decode($json, $assoc); } return $json; } http://php.net/manual/en/function.json-decode.php

« previous php.notes (#193803) next »