2

I'd like to implement a custom REST endpoint that can also return an empty object. However, in the case where it should return an empty object, the empty associative array returned by the callback is transformed to an empty array.

How can I force the endpoint to transform the array into an object like I can in json_encode by setting the JSON_FORCE_OBJECT flag?

function rest_cb() {
    return array();  // this will result in the REST response [] but {} is required
}

function on_rest_api_init() {
    register_rest_route('ns/v1', 'empty-object', 'rest_cb');
}
  • just return json? and check for string type – inarilo Jan 6 '18 at 13:14
  • There is no built-in json data type so I can't return json "itself". I only could return encoded json which would end in a string as the type of the return value. – felixlinker Jan 6 '18 at 13:22
2

Found the solution: By casting the return value to an object, it is ensured that in case of an empty array, an empty object will be returned on REST request.

Enhancing on my initial example, this code would work:

function rest_cb() {
    return (object) array();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.