WP_REST_Request::parse_json_params() WordPress Method

The parse_json_params() method is used to parse JSON parameters from a WP_REST_Request object. This is useful for handling JSON-encoded request bodies or query parameters.

WP_REST_Request::parse_json_params() #

Parses the JSON parameters.


Description

Avoids parsing the JSON data until we need to access it.


Top ↑

Return

(true|WP_Error) True if the JSON data was passed or no JSON data was provided, WP_Error if invalid JSON was passed.


Top ↑

Source

File: wp-includes/rest-api/class-wp-rest-request.php

	protected function parse_json_params() {
		if ( $this->parsed_json ) {
			return true;
		}

		$this->parsed_json = true;

		// Check that we actually got JSON.
		if ( ! $this->is_json_content_type() ) {
			return true;
		}

		$body = $this->get_body();
		if ( empty( $body ) ) {
			return true;
		}

		$params = json_decode( $body, true );

		/*
		 * Check for a parsing error.
		 */
		if ( null === $params && JSON_ERROR_NONE !== json_last_error() ) {
			// Ensure subsequent calls receive error instance.
			$this->parsed_json = false;

			$error_data = array(
				'status'             => WP_Http::BAD_REQUEST,
				'json_error_code'    => json_last_error(),
				'json_error_message' => json_last_error_msg(),
			);

			return new WP_Error( 'rest_invalid_json', __( 'Invalid JSON body passed.' ), $error_data );
		}

		$this->params['JSON'] = $params;

		return true;
	}


Top ↑

Changelog

Changelog
VersionDescription
4.7.0Returns error instance if value cannot be decoded.
4.4.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.