Last active
December 19, 2015 16:29
-
-
Save attitude/5984199 to your computer and use it in GitHub Desktop.
Decodes JSON string if needed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Decodes JSON string if needed | |
* | |
* @uses json_decode() | |
* @author Martin Adamko <@martin_adamko> | |
* @licence The MIT Licence <http://opensource.org/licenses/MIT> | |
* | |
* @param string $str String to decode if needed | |
* @param bool $assoc When TRUE, returned objects will be converted into associative arrays | |
* @param int $depth User specified recursion depth | |
* @param int $options Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats) | |
* @returns mixed | |
* | |
*/ | |
function maybe_decode_json($str, $assoc = false, $depth = 512, $options = 0) | |
{ | |
if (!is_string($str)) { | |
return $str; | |
} | |
// Trim it | |
$str = trim($str); | |
// Nothing to do with an empty string | |
if (strlen($str)===0) { | |
return ''; | |
} | |
// Any "null" string would return NULL (decoding error returns also NULL) | |
if ($str==='null') { | |
return null; | |
} | |
// Decode it | |
$data = json_decode($str, $assoc, $depth, $options); | |
// Decoding error | |
if ($data===null) { | |
return $str; | |
} | |
// Success | |
return $data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment