在Postman和jQuery中,我都会以
的形式获得回复{"key1": "value1", "key2": "value2"}null
那个尾随的null正在弄乱那些试图在客户端解析它的东西,我无法弄清楚它来自哪里。如果我在error_log
之前echo
编码的JSON,那么没有尾随空值,所以我认为它是一个字符串终结符,但我并不认为PHP使用以null结尾的字符串。我如何摆脱这些空值?
正在编码并返回的对象:
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
];
}
实际的return语句只是echo(json_encode($retval));
答案 0 :(得分:1)
一旦PHP文件执行完毕,你必须手动退出或返回而不是回显,否则它会隐式返回NULL
并弄乱一切。经验教训。
答案 1 :(得分:0)
可能不是最优雅的……但是这救了我:
function removeTrailingNulls(__str){
var sanitized = __str;
var lastCharIndex = sanitized.length - 1;
var lastChar = sanitized[lastCharIndex];
var lastCharCode = lastChar.charCodeAt(0);
var isWeirdNullSpace = lastCharCode === 0;
console.log('checking last char (' + lastChar + ') code: ' + lastCharCode + '...null space end?' + isWeirdNullSpace);
var loopCount = 0;
while(isWeirdNullSpace){
sanitized = sanitized.substring(0, sanitized.length-1);
lastChar = sanitized[sanitized.length-1];
lastCharCode = lastChar.charCodeAt(0);
isWeirdNullSpace = lastCharCode === 0;
loopCount++;
if(loopCount>100) break; // prevent infinite loops just in case.
}
return String(sanitized);
}