wp_json_encode()WP 4.1.0

Encode a variable into JSON, with some sanity checks. Checks strings and translates them to UTF-8.

The passed variable can be any type of data: array, string, object, number, etc.

Works based on PHP function json_encode().

Used By: wp_send_json()
1 time — 0.000001 sec (speed of light) | 50000 times — 0.09 sec (speed of light) | PHP 7.2.5, WP 4.9.8

No Hooks.

Return

String|false. The JSON encoded string, or false if it cannot be encoded.

Usage

wp_json_encode( $data, $options, $depth );
$data(mixed) (required)
Variable (usually an array or object) to encode as JSON.
$options(int)

Options to be passed to json_encode().

Constants that can be combined with | (bit mask):

JSON_HEX_QUOT
JSON_HEX_TAG
JSON_HEX_AMP
JSON_HEX_APOS
JSON_NUMERIC_CHECK
JSON_PRETTY_PRINT
JSON_UNESCAPED_SLASHES
JSON_FORCE_OBJECT
JSON_PRESERVE_ZERO_FRACTION
JSON_UNESCAPED_UNICODE
JSON_PARTIAL_OUTPUT_ON_ERROR

The value of each constant is explained on the JSON constants page.

Default: 0

$depth(int)
Maximum depth to walk through $data. Must be greater than 0.
Default: 512

Examples

0

#1 Demonstration of work

wp_json_encode( 'one' ); // "one"

wp_json_encode( 2 ); // 2

wp_json_encode( array( 1, 'two' ) ); // [1,"two"]

wp_json_encode( (object) array( 1, 'two' ) ); // {"0":1,"1":"two"}

Changelog

Since 4.1.0 Introduced.
Since 5.3.0 No longer handles support for PHP < 5.6.
Since 6.5.0 The $data parameter has been renamed to $value and the $options parameter to $flags for parity with PHP.

wp_json_encode() code WP 6.5.2

function wp_json_encode( $value, $flags = 0, $depth = 512 ) {
	$json = json_encode( $value, $flags, $depth );

	// If json_encode() was successful, no need to do more confidence checking.
	if ( false !== $json ) {
		return $json;
	}

	try {
		$value = _wp_json_sanity_check( $value, $depth );
	} catch ( Exception $e ) {
		return false;
	}

	return json_encode( $value, $flags, $depth );
}