WordPress at a glance

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().

Is the basis for: wp_send_json()
✈ 1 time = 0.000001s = speed of light | 50000 times = 0.09s = 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().

Constatnt 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

#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.

Code of wp json encode: wp-includes/functions.php WP 5.4.2

<?php
function wp_json_encode( $data, $options = 0, $depth = 512 ) {
	$json = json_encode( $data, $options, $depth );

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

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

	return json_encode( $data, $options, $depth );
}

Related Functions

From tag: AJAX

More from tag: PHP analogues (PHP functions replacement)

More from category: Helper Functions

No comments
        Log In . Register