Created
March 29, 2017 21:27
-
-
Save mtdowling/ed5ea633ec8358e6d2d399a8c0aa1220 to your computer and use it in GitHub Desktop.
Check if a value can be json_decoded
This file contains hidden or 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 | |
function try_json_encode($data) | |
{ | |
json_encode($data); | |
return (json_last_error() == JSON_ERROR_NONE); | |
} | |
function json_encode_type_check($data) | |
{ | |
static $validTypes = [ | |
'string' => true, | |
'integer' => true, | |
'double' => true, | |
'boolean' => true, | |
'array' => true, | |
'null' => true, | |
]; | |
$type = gettype($data); | |
return isset($validTypes[$type]) | |
|| $type == 'object' and $data instanceof JsonSerializable; | |
} | |
function benchmark($f, $iterations, ...$args) | |
{ | |
$startTime = microtime(true); | |
for ($i = 0; $i < $iterations; $i++) { | |
$f(...$args); | |
} | |
return ((microtime(true) - $startTime) / $iterations) * 1e9; | |
} | |
$iterations = 10000; | |
$cases = [ | |
'associative' => ['foo' => ['bar', 'baz', ['bam' => false]]], | |
'boolean' => true, | |
'string' => 'foobaz', | |
'number' => -1, | |
'deep assoc' => ['foo' => ['bar', 'baz', ['bam' => false]], ['foo' => ['bar', 'baz', ['bam' => false]]]], | |
]; | |
$benches = ['try_json_encode', 'json_encode_type_check']; | |
foreach ($cases as $caseName => $case) { | |
foreach ($benches as $bench) { | |
$result = benchmark($bench, $iterations, $case); | |
printf("%-20s %-30s: %-20f ns/iter\n", $caseName, $bench, $result); | |
} | |
echo "----\n"; | |
} |
There can be objects wich are not instances of JsonSerializable which can be json_encoded.
<?php
$obj = new StdClass();
$obj->a = "b";
var_dump($obj instanceof JsonSerializable);
var_dump(json_encode($obj));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: