wp_json_file_decode()WP 5.9.0

Reads and decodes (parses) the specified JSON file.

No Hooks.

Returns

Mixed.

  • Object/array/string/number/bool - data encoded in the JSON file as an object or associative array.

  • null - will return null if the file is not found, and will log the message File %s doesn't exist! in the error log. It will also return null if the file's contents cannot be decoded and will log the error Error when decoding a JSON file at path %1$s: %2$s.

Usage

wp_json_file_decode( $filename, $options );
$filename(string) (required)
Path to the JSON file.
$options(array)

Options used with json_decode().

Default: array()

  • associative(true|false)

    • true - JSON objects will be returned as associative arrays.
    • false - JSON objects will be returned as objects.

    Default: false

Examples

-1

#1 Get the contents of the json file as an associative array

$path_file = '/path/to/data.json';
$decoded_file = wp_json_file_decode( $path_file, [ 'associative' => true ] );

Changelog

Since 5.9.0 Introduced.

wp_json_file_decode() code WP 6.9.1

function wp_json_file_decode( $filename, $options = array() ) {
	$result   = null;
	$filename = wp_normalize_path( realpath( $filename ) );

	if ( ! $filename ) {
		wp_trigger_error(
			__FUNCTION__,
			sprintf(
				/* translators: %s: Path to the JSON file. */
				__( "File %s doesn't exist!" ),
				$filename
			)
		);
		return $result;
	}

	$options      = wp_parse_args( $options, array( 'associative' => false ) );
	$decoded_file = json_decode( file_get_contents( $filename ), $options['associative'] );

	if ( JSON_ERROR_NONE !== json_last_error() ) {
		wp_trigger_error(
			__FUNCTION__,
			sprintf(
				/* translators: 1: Path to the JSON file, 2: Error message. */
				__( 'Error when decoding a JSON file at path %1$s: %2$s' ),
				$filename,
				json_last_error_msg()
			)
		);
		return $result;
	}

	return $decoded_file;
}