Encoding flag

By default, only objects and arrays can be encoded directly, since they are the only valid root values of a JSON text. To encode any JSON value, use the JSON_ENCODE_ANY flag.

By default, the output has no newlines, and spaces are used between array and object elements for a readable output. This behavior can be altered by using the JSON_INDENT and JSON_COMPACT flags described below. A newline is never appended to the end of the encoded JSON data.

Take a flags parameter that controls some aspects of how the data is encoded. Its default value is 0. The following macros can be ORed together to obtain flags.

  • JSON_INDENT(n)
  • Pretty-print the result, using newlines between array and object items, and indenting with n spaces. The valid range for n is between 0 and 31 (inclusive), other values result in an undefined output. If JSON_INDENT is not used or n is 0, no newlines are inserted between array and object items.

    The JSON_MAX_INDENT constant defines the maximum indentation that can be used, and its value is 31.

  • JSON_COMPACT
  • This flag enables a compact representation, i.e. sets the separator between array and object items to "," and between object keys and values to ":". Without this flag, the corresponding separators are ", " and ": " for more readable output.

  • JSON_ENCODE_ANY
  • Specifying this flag makes it possible to encode any JSON value on its own. Without it, only objects and arrays can be passed as the json value to the encoding functions.

Reference

See below for details on other encoding flags.


Last updated: 2022/01/26