函数文档

wp_json_encode()

💡 云策文档标注

概述

wp_json_encode() 是 WordPress 核心函数,用于将变量编码为 JSON 字符串,并提供额外的可靠性检查。它基于 PHP 的 json_encode() 函数,但在编码失败时会尝试通过 _wp_json_sanity_check() 进行修复。

关键要点

  • 函数签名:wp_json_encode( $value, $flags = 0, $depth = 512 )
  • 参数:$value(必需,要编码的变量,通常为数组或对象),$flags(可选,传递给 json_encode() 的选项,默认 0),$depth(可选,遍历 $value 的最大深度,必须大于 0,默认 512)
  • 返回值:成功时返回 JSON 编码字符串,失败时返回 false
  • 内部机制:先调用 json_encode(),若失败则使用 _wp_json_sanity_check() 清理数据后重试
  • 兼容性:从 WordPress 4.1.0 引入,6.5.0 版本重命名参数以与 PHP 保持一致

代码示例

function get_json() {
    $out            = array();
    $out['options'] = array( 'option-1', 'option-2' );
    $out['content'] = 'content example';
    return wp_json_encode( $out );
}

📄 原文内容

Encodes a variable into JSON, with some confidence checks.

Parameters

$valuemixedrequired
Variable (usually an array or object) to encode as JSON.
$flagsintoptional
Options to be passed to json_encode(). Default 0.
$depthintoptional
Maximum depth to walk through $value. Must be greater than 0.

Default:512

Return

string|false The JSON encoded string, or false if it cannot be encoded.

Source

function wp_json_encode( $value, $flags = 0, $depth = 512 ) {
	$json = json_encode( $value, $flags, $depth );

	// If json_encode() was successful, no need to do more confidence checking.
	if ( false !== $json ) {
		return $json;
	}

	try {
		$value = _wp_json_sanity_check( $value, $depth );
	} catch ( Exception $e ) {
		return false;
	}

	return json_encode( $value, $flags, $depth );
}

Changelog

Version Description
6.5.0 The $data parameter has been renamed to $value and the $options parameter to $flags for parity with PHP.
5.3.0 No longer handles support for PHP < 5.6.
4.1.0 Introduced.

User Contributed Notes