| | 2615 | * Encode a variable into JSON, with some sanity checks |
| | 2616 | * |
| | 2617 | * @since 4.0 |
| | 2618 | * |
| | 2619 | * @param mixed $data Variable (usually an array or object) to encode as JSON |
| | 2620 | * |
| | 2621 | * @return string The JSON encoded string |
| | 2622 | */ |
| | 2623 | function wp_json_encode( $data ) { |
| | 2624 | $try = json_encode( $data ); |
| | 2625 | |
| | 2626 | if ( ! empty( $try ) ) { |
| | 2627 | // If json_encode was successful, no need to do more sanity checking |
| | 2628 | return $try; |
| | 2629 | } |
| | 2630 | |
| | 2631 | return json_encode( _wp_json_sanity_check( $data ) ); |
| | 2632 | } |
| | 2633 | |
| | 2634 | function _wp_json_sanity_check( $data ) { |
| | 2635 | if ( is_string( $data ) ) { |
| | 2636 | $data = wp_check_invalid_utf8( $data, true ); |
| | 2637 | } else if ( is_array( $data ) ) { |
| | 2638 | foreach ( $data as $id => $el ) { |
| | 2639 | $data[ $id ] = _wp_json_sanity_check( $el, $_depth + 1 ); |
| | 2640 | } |
| | 2641 | } else if ( is_object( $data ) ) { |
| | 2642 | foreach ( $data as $id => $el ) { |
| | 2643 | $data->$id = _wp_json_sanity_check( $el, $_depth + 1 ); |
| | 2644 | } |
| | 2645 | } |
| | 2646 | |
| | 2647 | return $data; |
| | 2648 | } |
| | 2649 | |
| | 2650 | /** |