Json encode

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":"info@tplix.com"}.

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"}
Was this article helpful?