reasonableframework/helper/json.format.php

70 lines
2.2 KiB
PHP
Raw Normal View History

2019-10-12 15:21:20 +00:00
<?php
2020-01-27 08:04:12 +00:00
// @created_on 2019-10-13
// @updated_on 2020-01-27
2022-11-25 14:15:20 +00:00
// @author Go Namhyeon <abuse@catswords.net>
2019-10-12 15:21:20 +00:00
if(!is_fn("json_decode_ex")) {
2019-10-12 15:21:20 +00:00
function json_decode_ex($data, $options=array()) {
$result = false;
2020-01-27 08:04:12 +00:00
2020-01-14 02:30:15 +00:00
$is_assoc = array_key_equals("assoc", $options, true);
2019-10-12 15:21:20 +00:00
$invalid_fn = array(
"NO_FUNCTION_JSON_DECODE" => "json_decode",
"NO_FUNCTION_JSON_LAST_ERROR" => "json_last_error",
);
2019-12-19 02:04:10 +00:00
$error = check_invalid_function($invalid_fn);
2020-01-27 08:04:12 +00:00
if($error == JSON_ERROR_NONE) {
2020-01-14 02:30:15 +00:00
if($is_assoc) {
$result = json_decode($data, true);
} else {
$result = json_decode($data);
}
2020-01-27 08:04:12 +00:00
} else {
$result = new stdClass();
$result->error = $error;
2019-10-12 15:21:20 +00:00
}
return $result;
}
}
if(!is_fn("json_encode_ex")) {
2019-10-12 15:21:20 +00:00
function json_encode_ex($data, $options=array()) {
$result = false;
2020-01-14 02:28:39 +00:00
$is_adaptive = array_key_equals("adaptive", $options, true);
2020-01-27 08:04:12 +00:00
$is_pretty = array_key_equals("pretty", $options, true);
$invalid_fn = array(
"NO_FUNCTION_JSON_ENCODE" => "json_decode",
"NO_FUNCTION_JSON_LAST_ERROR" => "json_last_error",
);
$error = check_invalid_function($invalid_fn);
if($error == JSON_ERROR_NONE) {
if($is_adaptive) {
// 2018-06-01: Adaptive JSON is always quotes without escape non-ascii characters
$lines = array();
foreach($data as $k=>$v) {
if(is_array($v)) {
$lines[] = sprintf("\"%s\":%s", make_safe_argument($k), get_adaptive_json($v));
} else {
$lines[] = sprintf("\"%s\":\"%s\"", make_safe_argument($k), make_safe_argument($v));
}
}
$result = "{" . implode(",", $lines) . "}";
} else {
if($is_pretty) {
$result = json_encode($data, JSON_PRETTY_PRINT);
2019-10-12 15:21:20 +00:00
} else {
2020-01-27 08:04:12 +00:00
$result = json_encode($data);
2019-10-12 15:21:20 +00:00
}
}
} else {
2020-01-27 08:04:12 +00:00
$result = sprintf("{\"error\": \"%s\"}", $error);
2019-10-12 15:21:20 +00:00
}
2020-01-14 02:28:39 +00:00
2019-10-12 15:21:20 +00:00
return $result;
}
}