rosavox/lib/alveolata/json/functions.php
2025-05-23 07:33:29 +00:00

46 lines
842 B
PHP

<?php
namespace alveolata\json;
// require_once(DIR_ALVEOLATA . '/definitions.php');
/**
* @param mixed $value
* @return string
* @author Christian Fraß <frass@greenscale.de>
*/
function encode(
$value,
bool $formatted = false
) : string
{
$string = json_encode($value, $formatted ? JSON_PRETTY_PRINT : 0);
if (json_last_error() !== JSON_ERROR_NONE) {
throw (new \Exception('json not encodable: ' . json_last_error_msg()));
}
else {
return $string;
}
}
/**
* @param string $string
* @return mixed
* @throws \Exception if not decodable
* @author Christian Fraß <frass@greenscale.de>
*/
function decode(
string $string
)
{
$value = json_decode($string, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw (new \Exception('json not decodable: ' . json_last_error_msg()));
}
else {
return $value;
}
}