TPLix

No results for ""

Json Encode

3 min read Jun 2, 2026
--- title: json_encode autoseo: enabled: true theme: learn2 child_type: default admin: children_display_order: collection visible: true ---

json_encode — Transforms a value into a valid JSON string.

Basic Usage:
{$user|json_encode}

Depending on the value of $user this would return a string in JSON-format, e.g. {"username":"tplix","email":"[email protected]"}.

Parameters:
Parameter Type Required Description
1 int No bitmask of flags, directly passed to PHP's json_encode
2 int No Depth

If you curious of the numeric values of the constants, as of JSON 1.2.1, the constants have the following values (not that you should use the numbers directly):

Display Numeric Values Hide Numeric Values

JSON_HEX_TAG = 1
JSON_HEX_AMP = 2
JSON_HEX_APOS = 4
JSON_HEX_QUOT = 8
JSON_FORCE_OBJECT = 16
JSON_NUMERIC_CHECK = 32
JSON_UNESCAPED_SLASHES = 64
JSON_PRETTY_PRINT = 128
JSON_UNESCAPED_UNICODE = 256
JSON_ERROR_DEPTH = 1
JSON_ERROR_STATE_MISMATCH = 2
JSON_ERROR_CTRL_CHAR = 3
JSON_ERROR_SYNTAX = 4
JSON_ERROR_UTF8 = 5
JSON_OBJECT_AS_ARRAY = 1
JSON_BIGINT_AS_STRING = 2

By passing 16 as the second parameter, you can force json_encode to always format the JSON-string as an object. Without it, an array $myArray = ["a","b"] would be formatted as a javascript array:


{$myArray|json_encode} # renders: ["a","b"]
{$myArray|json_encode:16} # renders: {"0":"a","1":"b"}

Leave a Comment

Not published. Used to notify you on approval.

Comments are moderated before appearing.