javascript - 無法解析有效的 JSON
我的 API 使用 PHP Silex 發回像這樣的 JSON 回應:
{"response":true,"message":"Bla","userId":"AAA"}
但是我無法在我的 Typescript 前端解析它
this.authService.login(body).then((result : any) => {
console.log(result.data); // => {"response":true,"message":"Bla","userId":"AAA"}
let parsed = JSON.parse(result.data);
console.log(parsed.message); // => throws "SyntaxError: Unexpected token in JSON at position 0\n at JSON.parse (<anonymous>)
我使用 PHP 和 Silex 框架的 PHP 端點:
$app->post('/user/login', function (Request $request) use ($app, $config) {
$email = $request->request->get('user-email');
$password = $request->request->get('user-password');
$rsp = loginUser($email,$password);
return $app->json($rsp);
});
當嘗試將 json 對象硬編碼到代碼中時,它確實會解析!
更新解決方案 我必須對 result.data 使用 trim() 來移除空白,因為有時回應中會帶有空白,而 JSON 無法接受。謝謝大家的幫助。
答案#1
解決方案
我使用了 result.data.trim() 才讓它工作,不知怎的,回應中有空白,而 JSON 不喜歡這樣。
答案#2
你的 PHP 程式碼中某處可能有一個 \u0000 字元。
當你從 PHP 獲取 JSON 字串時,儘量立即移除這些字元:
this.authService.login(body).then((result : any) => {
string = result.data.replace("\u0000", "");
string = string.replace("\\u0000", "");
let parsed = JSON.parse(string);
