JSON 响应字符串以 "null" 结尾
JSON response string ends with "null"
在 Postman 和 jQuery 中,我收到的回复都是
{"key1": "value1", "key2": "value2"}null
尾随的 null 干扰了任何试图在客户端解析它的东西,我无法弄清楚它来自哪里。如果我在 echo
之前 error_log
编码 JSON ,则没有尾随空值,所以我认为它是一个字符串终止符,但我不认为 PHP 使用以 null 结尾的字符串。我如何摆脱这些空值?
正在编码和 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
];
}
实际的 return 语句只是 echo(json_encode($retval));
一旦 PHP 文件执行完毕,你必须手动退出或 return 而不是回显,否则它会 return NULL
隐含地把一切搞砸.吸取教训。
可能不是最优雅的...但这救了我:
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);
}
在 Postman 和 jQuery 中,我收到的回复都是
{"key1": "value1", "key2": "value2"}null
尾随的 null 干扰了任何试图在客户端解析它的东西,我无法弄清楚它来自哪里。如果我在 echo
之前 error_log
编码 JSON ,则没有尾随空值,所以我认为它是一个字符串终止符,但我不认为 PHP 使用以 null 结尾的字符串。我如何摆脱这些空值?
正在编码和 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
];
}
实际的 return 语句只是 echo(json_encode($retval));
一旦 PHP 文件执行完毕,你必须手动退出或 return 而不是回显,否则它会 return NULL
隐含地把一切搞砸.吸取教训。
可能不是最优雅的...但这救了我:
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);
}