wp_json_encode() WP 4.1.0
Encode a variable into JSON, with some sanity checks. Checks strings and translates them to UTF-8.
The passed variable can be any type of data: array, string, object, number, etc.
Works based on PHP function json_encode().
Basis of: wp_send_json()
1 time = 0.000001s = speed of light | 50000 times = 0.09s = speed of light | PHP 7.2.5, WP 4.9.8
No Hooks.
Return
String/false. The JSON encoded string, or false if it cannot be encoded.
Usage
wp_json_encode( $data, $options, $depth );
- $data(mixed) (required)
- Variable (usually an array or object) to encode as JSON.
- $options(int)
Options to be passed to json_encode().
Constatnt that can be combined with
|
(bit mask): JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR. The value of each constant is explained on the JSON constants page.Default: 0
- $depth(int)
- Maximum depth to walk through $data. Must be greater than 0.
Default: 512
Examples
#1 Demonstration of work
wp_json_encode( 'one' ); // "one" wp_json_encode( 2 ); // 2 wp_json_encode( array( 1, 'two' ) ); // [1,"two"] wp_json_encode( (object) array( 1, 'two' ) ); // {"0":1,"1":"two"}
Changelog
Since 4.1.0 | Introduced. |
Since 5.3.0 | No longer handles support for PHP < 5.6. |
Code of wp_json_encode() wp json encode WP 5.6
function wp_json_encode( $data, $options = 0, $depth = 512 ) {
$json = json_encode( $data, $options, $depth );
// If json_encode() was successful, no need to do more sanity checking.
if ( false !== $json ) {
return $json;
}
try {
$data = _wp_json_sanity_check( $data, $depth );
} catch ( Exception $e ) {
return false;
}
return json_encode( $data, $options, $depth );
}Related Functions
From tag: AJAX
More from tag: PHP analogues (PHP functions replacement)
More from category: Helper Functions
- __return_empty_array()
- __return_empty_string()
- __return_false()
- __return_null()
- __return_true()
- __return_zero()
- build_query()
- get_page_hierarchy()
- get_temp_dir()
- human_readable_duration()
- is_email()
- is_php_version_compatible()
- is_serialized()
- is_serialized_string()
- is_wp_version_compatible()
- map_deep()
- maybe_serialize()
- maybe_unserialize()
- path_join()
- seems_utf8()
- stripslashes_deep()
- timer_stop()
- urlencode_deep()
- wp_array_slice_assoc()
- wp_debug_backtrace_summary()
- wp_extract_urls()
- wp_filter_object_list()
- wp_html_split()
- wp_is_json_request()
- wp_is_numeric_array()
- wp_is_uuid()
- wp_kses_array_lc()
- wp_kses_hair()
- wp_kses_uri_attributes()