Ticket #28786: 28786.3.diff
| File 28786.3.diff, 2.8 KB (added by , 12 years ago) |
|---|
-
src/wp-includes/functions.php
2612 2612 } 2613 2613 2614 2614 /** 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_array( $data ) ) { 2636 foreach ( $data as $id => $el ) { 2637 $data[ $id ] = _wp_json_sanity_check( $el, $_depth + 1 ); 2638 } 2639 } else if ( is_object( $data ) ) { 2640 foreach ( $data as $id => $el ) { 2641 $data->$id = _wp_json_sanity_check( $el, $_depth + 1 ); 2642 } 2643 } else if ( function_exists( 'mb_convert_encoding' ) ) { 2644 if ( mb_detect_encoding( $data ) ) { 2645 $data = mb_convert_encoding( $data, 'UTF-8', mb_detect_encoding( $data ) ); 2646 } else { 2647 $data = mb_convert_encoding( $data, 'UTF-8', 'auto' ); 2648 } 2649 } else { 2650 $data = wp_check_invalid_utf8( $data, true ); 2651 } 2652 2653 return $data; 2654 } 2655 2656 /** 2615 2657 * Send a JSON response back to an Ajax request. 2616 2658 * 2617 2659 * @since 3.5.0 … … 2621 2663 */ 2622 2664 function wp_send_json( $response ) { 2623 2665 @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) ); 2624 echo json_encode( $response );2666 echo wp_json_encode( $response ); 2625 2667 if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) 2626 2668 wp_die(); 2627 2669 else -
tests/phpunit/tests/functions.php
524 524 $this->assertCount( 8, $urls ); 525 525 $this->assertEquals( array_slice( $original_urls, 0, 8 ), $urls ); 526 526 } 527 528 /** 529 * @ticket 28786 530 */ 531 function test_wp_json_encode() { 532 $tests = array( 533 'a' => '"a"', 534 '这' => '"\u8fd9"', 535 ); 536 537 foreach ( $tests as $string => $json ) { 538 $this->assertEquals( wp_json_encode( $string ), $json ); 539 } 540 541 $charsets = mb_detect_order(); 542 if ( ! in_array( 'EUC-JP', $charsets ) ) { 543 $charsets[] = 'EUC-JP'; 544 mb_detect_order( $charsets ); 545 } 546 547 $eucjp = mb_convert_encoding( 'aあb', 'EUC-JP', 'UTF-8' ); 548 $utf8 = mb_convert_encoding( $eucjp, 'UTF-8', 'EUC-JP' ); 549 550 $this->assertEquals( 'aあb', $utf8 ); 551 552 $this->assertEquals( wp_json_encode( $eucjp ), '"a\u3042b"' ); 553 554 $this->assertEquals( wp_json_encode( array( 'a' ) ), '["a"]' ); 555 556 $object = new stdClass; 557 $object->a = 'b'; 558 $this->assertEquals( wp_json_encode( $object ), '{"a":"b"}' ); 559 } 527 560 }
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)