wp_json_encode

Encode a variable into JSON, with some sanity checks.

Description

(string|false) wp_json_encode( (mixed) $data, (int) $options = 0, (int) $depth = 512 ); 

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

  1. if ( !function_exists( 'wp_json_encode' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.php'; 
  3.  
  4. // Variable (usually an array or object) to encode as JSON. 
  5. $data = null; 
  6.  
  7. // Optional. Options to be passed to json_encode(). Default 0. 
  8. $options = -1; 
  9.  
  10. // Optional. Maximum depth to walk through $data. Must be 
  11. // greater than 0. Default 512. 
  12. $depth = 512; 
  13.  
  14. // NOTICE! Understand what this does before running. 
  15. $result = wp_json_encode($data, $options, $depth); 
  16.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/functions.php  
  1. function wp_json_encode( $data, $options = 0, $depth = 512 ) { 
  2. /** 
  3. * json_encode() has had extra params added over the years. 
  4. * $options was added in 5.3, and $depth in 5.5. 
  5. * We need to make sure we call it with the correct arguments. 
  6. */ 
  7. if ( version_compare( PHP_VERSION, '5.5', '>=' ) ) { 
  8. $args = array( $data, $options, $depth ); 
  9. } elseif ( version_compare( PHP_VERSION, '5.3', '>=' ) ) { 
  10. $args = array( $data, $options ); 
  11. } else { 
  12. $args = array( $data ); 
  13.  
  14. // Prepare the data for JSON serialization. 
  15. $args[0] = _wp_json_prepare_data( $data ); 
  16.  
  17. $json = @call_user_func_array( 'json_encode', $args ); 
  18.  
  19. // If json_encode() was successful, no need to do more sanity checking. 
  20. // ... unless we're in an old version of PHP, and json_encode() returned 
  21. // a string containing 'null'. Then we need to do more sanity checking. 
  22. if ( false !== $json && ( version_compare( PHP_VERSION, '5.5', '>=' ) || false === strpos( $json, 'null' ) ) ) { 
  23. return $json; 
  24.  
  25. try { 
  26. $args[0] = _wp_json_sanity_check( $data, $depth ); 
  27. } catch ( Exception $e ) { 
  28. return false; 
  29.  
  30. return call_user_func_array( 'json_encode', $args );