_wp_json_sanity_check

Perform sanity checks on data that shall be encoded to JSON.

Description

_wp_json_sanity_check( (mixed) $data, (int) $depth ); 

Parameters (2)

0. $data (mixed)
Variable (usually an array or object) to encode as JSON.
1. $depth (int)
Maximum depth to walk through $data. Must be greater than 0.

Usage

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

Defined (1)

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

/wp-includes/functions.php  
  1. function _wp_json_sanity_check( $data, $depth ) { 
  2. if ( $depth < 0 ) { 
  3. throw new Exception( 'Reached depth limit' ); 
  4.  
  5. if ( is_array( $data ) ) { 
  6. $output = array(); 
  7. foreach ( $data as $id => $el ) { 
  8. // Don't forget to sanitize the ID! 
  9. if ( is_string( $id ) ) { 
  10. $clean_id = _wp_json_convert_string( $id ); 
  11. } else { 
  12. $clean_id = $id; 
  13.  
  14. // Check the element type, so that we're only recursing if we really have to. 
  15. if ( is_array( $el ) || is_object( $el ) ) { 
  16. $output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 ); 
  17. } elseif ( is_string( $el ) ) { 
  18. $output[ $clean_id ] = _wp_json_convert_string( $el ); 
  19. } else { 
  20. $output[ $clean_id ] = $el; 
  21. } elseif ( is_object( $data ) ) { 
  22. $output = new stdClass; 
  23. foreach ( $data as $id => $el ) { 
  24. if ( is_string( $id ) ) { 
  25. $clean_id = _wp_json_convert_string( $id ); 
  26. } else { 
  27. $clean_id = $id; 
  28.  
  29. if ( is_array( $el ) || is_object( $el ) ) { 
  30. $output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 ); 
  31. } elseif ( is_string( $el ) ) { 
  32. $output->$clean_id = _wp_json_convert_string( $el ); 
  33. } else { 
  34. $output->$clean_id = $el; 
  35. } elseif ( is_string( $data ) ) { 
  36. return _wp_json_convert_string( $data ); 
  37. } else { 
  38. return $data; 
  39.  
  40. return $output;