0

Why do I get 0 when WP_REST_Request::get_json_params() parses a JSON body value of null?

I have a method which is responsible for turning a WP_REST_Request into another format which is acceptable for my business logic.

function prepare_item_for_database(WP_REST_Request $request): array
{
    $payload = $request->get_json_params();
    // ... validation
    return $payload;
}

When I have a request which includes null values, the WP_REST_Request::get_json_params() function creates PHP 0, instead of null. I get the following.

Why do I get 0 in the PHP array, instead of null?

HTTP POST Body

{
    "name": "s",
    "feature_id": null,
    "note_id": null
}

PHP Parsed Value

// What I get
Array
(
    [name] => s
    [feature_id] => 0
    [note_id] => 0
)

// What I expect
Array
(
    [name] => s
    [feature_id] => null
    [note_id] => null
)

The schema for the endpoint is like the following

[
    'properties' => [
        'name'  => [
            'type' => 'string'
        ],
        'feature_id' => [
            'type' => 'integer'
        ],
        'note_id' => [
            'type' => 'integer'
        ],
    ]
];
5
  • Which Wordpress version are you running? Testing this locally I get the expected value of null so I am think either it has to do with the version you are currently running or perhaps there is a filter involved? Can you show the schema for the rest endpoint? Commented Sep 9, 2022 at 20:56
  • Wordpress 6.0.2 & PHP 7.4.1. Schema does have "type": "integer" for these properties. Commented Sep 9, 2022 at 20:58
  • And.......changing the schema to 'type' => ['integer', 'null'], causes null to be parsed. So it was the schema. Commented Sep 9, 2022 at 21:06
  • 1
    Well then that is the reason, if you are using integer the params will be converted to integers and if you do intval(null) you will get 0. Commented Sep 9, 2022 at 21:06
  • @Cyclonecode Can you add this as an answer? Commented Sep 9, 2022 at 21:07

1 Answer 1

2

This is related to how you declare the parameter types for the endpoint. If you use integer then the parameters will be converted to integers, so in cases where a null value is being used you will get 0. The solution is to add support for both integer and null e.g.

'type' => ['integer', 'null'],

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.