_wp_json_sanity_check()WP 4.1.0

Performs confidence checks on data that shall be encoded to JSON.

Internal function — this function is designed to be used by the kernel itself. It is not recommended to use this function in your code.

No Hooks.

Return

Mixed. The sanitized data that shall be encoded to JSON.

Usage

_wp_json_sanity_check( $value, $depth );
$value(mixed) (required)
Variable (usually an array or object) to encode as JSON.
$depth(int) (required)
Maximum depth to walk through $value. Must be greater than 0.

Notes

Changelog

Since 4.1.0 Introduced.

_wp_json_sanity_check() code WP 6.5.2

function _wp_json_sanity_check( $value, $depth ) {
	if ( $depth < 0 ) {
		throw new Exception( 'Reached depth limit' );
	}

	if ( is_array( $value ) ) {
		$output = array();
		foreach ( $value as $id => $el ) {
			// Don't forget to sanitize the ID!
			if ( is_string( $id ) ) {
				$clean_id = _wp_json_convert_string( $id );
			} else {
				$clean_id = $id;
			}

			// Check the element type, so that we're only recursing if we really have to.
			if ( is_array( $el ) || is_object( $el ) ) {
				$output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 );
			} elseif ( is_string( $el ) ) {
				$output[ $clean_id ] = _wp_json_convert_string( $el );
			} else {
				$output[ $clean_id ] = $el;
			}
		}
	} elseif ( is_object( $value ) ) {
		$output = new stdClass();
		foreach ( $value as $id => $el ) {
			if ( is_string( $id ) ) {
				$clean_id = _wp_json_convert_string( $id );
			} else {
				$clean_id = $id;
			}

			if ( is_array( $el ) || is_object( $el ) ) {
				$output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 );
			} elseif ( is_string( $el ) ) {
				$output->$clean_id = _wp_json_convert_string( $el );
			} else {
				$output->$clean_id = $el;
			}
		}
	} elseif ( is_string( $value ) ) {
		return _wp_json_convert_string( $value );
	} else {
		return $value;
	}

	return $output;
}