Files
ave-cms/help/en/helpers/Json.md
T
2026-07-27 12:58:44 +03:00

2.0 KiB
Raw Blame History

Json - JSON

App\Helpers\Json - secure encode/decode with reasonable defaults and support Cyrillic alphabet.

use App\Helpers\Json;

Coding

###encode($data, $flags = 0) Regular coding.

###payload($value, $flags = JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) Encoding "for the API": readable Cyrillic, slashes are not escaped. Returns null for empty values (null, '', []) - convenient, so as not to drive empty space.

echo Json::payload(['title' => 'Кресло', 'price' => 100]);
// {"title":"Кресло","price":100}   ← без \u04..
Json::payload([]);   // null

Decoding

###decode($json, $assoc = true) By default - to an array; $assoc = false - to the object.

$data = Json::decode($raw);          // массив
$obj  = Json::decode($raw, false);   // объект

###toArray($value, array $default = []) An array is guaranteed: if its already an array, it will be returned as is, if its a string, it will be parsed, in case of error - $default. Ideal for JSON database fields.

$settings = Json::toArray($row['settings']);          // всегда массив
$tags     = Json::toArray($row['tags'], ['default']);

Auxiliary

Method Destination
show(array $array, $shutdown = false, $cyrillic = false) Output JSON (and optionally complete the request).
cyrillic($data) Make escaped Cyrillic alphabet readable.
fix($json) An attempt to “fix” crooked JSON (single quotes, garbage).
$data = Json::decode(Json::fix($messyJson));   // last resort для «грязного» входа

Recipes

Reading JSON settings from a database string without crashes:

$config = Json::toArray($row['config']);
$perPage = isset($config['per_page']) ? (int) $config['per_page'] : 25;

For a full HTTP response, it is more convenient to Response::json() - it puts headers and code. Json - about serialization as such.