Search code examples
phpjsonwordpressrestwordpress-plugin-creation

JSON response string ends with "null"


In both Postman and jQuery, I'm getting responses in the form

{"key1": "value1", "key2": "value2"}null

That trailing null is messing with anything that tries to parse it client-side and I can't figure out where it's coming from. If I error_log the encoded JSON before echoing it, there's no trailing null, so I assume that it's a string terminator, but I didn't think that PHP used null-terminated strings. How do I get rid of these nulls?

The object being encoded and returned:

public function jsonSerialize()
{
    return [
        'internal_id' => $this->internal_id, //int
        'friendly_name' => $this->friendly_name, //string
        'external_id' => $this->external_id, //string
        'picture' => $this->picture //string
    ];
}

The actual return statement is just echo(json_encode($retval));


Solution

  • Once a PHP file has executed, you have to exit manually or return instead of echoing, otherwise it'll return NULL implicitly and mess everything up. Lesson learned.