Make WordPress Core

Ticket #33982: 33982-jsonserialize.diff

File 33982-jsonserialize.diff, 1.7 KB (added by rmccue, 10 years ago)

Add JsonSerializable support to wp_json_encode

  • src/wp-includes/functions.php

     
    26852685                $args = array( $data );
    26862686        }
    26872687
     2688        // Prepare the data for JSON serialization.
     2689        $data = _wp_json_prepare_data( $data );
     2690
    26882691        $json = @call_user_func_array( 'json_encode', $args );
    26892692
    26902693        // If json_encode() was successful, no need to do more sanity checking.
     
    27992802}
    28002803
    28012804/**
     2805 * Prepares response data to be serialized to JSON.
     2806 *
     2807 * This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
     2808 *
     2809 * @ignore
     2810 * @since 4.4.0
     2811 * @access private
     2812 *
     2813 * @param mixed $data Native representation.
     2814 * @return array|string Data ready for `json_encode()`.
     2815 */
     2816function _wp_json_prepare_data( $data ) {
     2817        if ( ! defined( 'WP_JSON_SERIALIZE_COMPATIBLE' ) || WP_JSON_SERIALIZE_COMPATIBLE === false ) {
     2818                return $data;
     2819        }
     2820
     2821        switch ( gettype( $data ) ) {
     2822                case 'boolean':
     2823                case 'integer':
     2824                case 'double':
     2825                case 'string':
     2826                case 'NULL':
     2827                        // These values can be passed through.
     2828                        return $data;
     2829
     2830                case 'array':
     2831                        // Arrays must be mapped in case they also return objects.
     2832                        return array_map( '_wp_json_prepare_data', $data );
     2833
     2834                case 'object':
     2835                        if ( $data instanceof JsonSerializable ) {
     2836                                $data = $data->jsonSerialize();
     2837                        } else {
     2838                                $data = get_object_vars( $data );
     2839                        }
     2840
     2841                        // Now, pass the array (or whatever was returned from jsonSerialize through).
     2842                        return _wp_json_prepare_data( $data );
     2843
     2844                default:
     2845                        return null;
     2846        }
     2847}
     2848
     2849/**
    28022850 * Send a JSON response back to an Ajax request.
    28032851 *
    28042852 * @since 3.5.0