wp_json_encode
Encode a variable into JSON, with some sanity checks.
Description
Returns (string|false)
The JSON encoded string, or false if it cannot be encoded.
Parameters (3)
- 0. $data (mixed)
- Variable (usually an array or object) to encode as JSON.
- 1. $options — Optional. (int)
- Options to be passed to
json_encode(…)
. Default 0. - 2. $depth — Optional. (int) =>
512
- Maximum depth to walk through
$data
. Must be greater than 0. Default 512.
Usage
if ( !function_exists( 'wp_json_encode' ) ) { require_once ABSPATH . WPINC . '/functions.php'; } // Variable (usually an array or object) to encode as JSON. $data = null; // Optional. Options to be passed to json_encode(). Default 0. $options = -1; // Optional. Maximum depth to walk through $data. Must be // greater than 0. Default 512. $depth = 512; // NOTICE! Understand what this does before running. $result = wp_json_encode($data, $options, $depth);
Defined (1)
The function is defined in the following location(s).
- /wp-includes/functions.php
- function wp_json_encode( $data, $options = 0, $depth = 512 ) {
- /**
- * json_encode() has had extra params added over the years.
- * $options was added in 5.3, and $depth in 5.5.
- * We need to make sure we call it with the correct arguments.
- */
- if ( version_compare( PHP_VERSION, '5.5', '>=' ) ) {
- $args = array( $data, $options, $depth );
- } elseif ( version_compare( PHP_VERSION, '5.3', '>=' ) ) {
- $args = array( $data, $options );
- } else {
- $args = array( $data );
- }
- // Prepare the data for JSON serialization.
- $args[0] = _wp_json_prepare_data( $data );
- $json = @call_user_func_array( 'json_encode', $args );
- // If json_encode() was successful, no need to do more sanity checking.
- // ... unless we're in an old version of PHP, and json_encode() returned
- // a string containing 'null'. Then we need to do more sanity checking.
- if ( false !== $json && ( version_compare( PHP_VERSION, '5.5', '>=' ) || false === strpos( $json, 'null' ) ) ) {
- return $json;
- }
- try {
- $args[0] = _wp_json_sanity_check( $data, $depth );
- } catch ( Exception $e ) {
- return false;
- }
- return call_user_func_array( 'json_encode', $args );
- }