_wp_json_prepare_data

Prepares response data to be serialized to JSON.

Description

(bool|int|float|null|string|array) _wp_json_prepare_data( (mixed) $data ); 

This supports the JsonSerializable interface for PHP 5.2-5.3 as well.

Returns (bool|int|float|null|string|array)

Data ready for `json_encode()`.

Parameters (1)

0. $data (mixed)
Native representation.

Usage

  1. if ( !function_exists( '_wp_json_prepare_data' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.php'; 
  3.  
  4. // Native representation. 
  5. $data = null; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = _wp_json_prepare_data($data); 
  9.  

Defined (1)

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

/wp-includes/functions.php  
  1. function _wp_json_prepare_data( $data ) { 
  2. if ( ! defined( 'WP_JSON_SERIALIZE_COMPATIBLE' ) || WP_JSON_SERIALIZE_COMPATIBLE === false ) { 
  3. return $data; 
  4.  
  5. switch ( gettype( $data ) ) { 
  6. case 'boolean': 
  7. case 'integer': 
  8. case 'double': 
  9. case 'string': 
  10. case 'NULL': 
  11. // These values can be passed through. 
  12. return $data; 
  13.  
  14. case 'array': 
  15. // Arrays must be mapped in case they also return objects. 
  16. return array_map( '_wp_json_prepare_data', $data ); 
  17.  
  18. case 'object': 
  19. // If this is an incomplete object (__PHP_Incomplete_Class), bail. 
  20. if ( ! is_object( $data ) ) { 
  21. return null; 
  22.  
  23. if ( $data instanceof JsonSerializable ) { 
  24. $data = $data->jsonSerialize(); 
  25. } else { 
  26. $data = get_object_vars( $data ); 
  27.  
  28. // Now, pass the array (or whatever was returned from jsonSerialize through). 
  29. return _wp_json_prepare_data( $data ); 
  30.  
  31. default: 
  32. return null;