2016-07-26 120 views
0

我想閱讀_body中的錯誤消息。如何在此JSON中訪問此密鑰的此值?

目前,我做的是:

的console.log(message._body.error);

但是,我越來越未定義。

當我做console.log(message._body);

我得到「{」代碼「:141,」錯誤「:」這個電話號碼已經存在!「}」

var message = { 
"_body":"{"code":141,"error":"This phone number exists already!"}", 
"status":400, 
"ok":false, 
"statusText":"Bad Request", 
"type":2 
}; 

通過以下的方式來形成這樣的後臺,我可以」 t更改其格式既不刪除雙引號

"_body":"{"code":141,"error":"This phone number exists already!"}" 

如何讀取錯誤消息?

+0

如果這是一個真正的'JSON'對象,那麼你應該'parse'。它首先('JSON.parse(obj)') –

回答

0

在你的情況在從後端獲取錯誤之後,需要使用json()方法將其轉換爲json。

下一個能很好地工作你:

error.json()錯誤

console.log(error.json().error) 
+0

你釘了它!感謝一個looot! –

0

刪除你的雙引號。做到這一點...

"_body":{"code":141,"error":"This phone number exists already!"},

這裏是一個小提琴...

https://jsfiddle.net/cmht6u8f/1/

+0

就是這樣,我不能控制它,因爲它來自後端! –

+0

您必須展示更多代碼,獲取代碼和/或修復後端,因爲您顯示的語法無效。這甚至不是一個適當的字符串。 – gfrobenius

1

這聽起來像你有一個包含有效的JSON的字符串的屬性。

您需要致電JSON.parse()將其轉換爲實際對象。

+0

它不是有效的JSON字符串。 – gfrobenius

+0

@gfrobenius:AFAICT,它是,但OP沒有正確粘貼它。 – SLaks

0
  1. 你必須修復JSON到它的正確形式:

    var message = { 
        "_body":'{"code":141,"error":"This phone number exists already!"}', 
        "status":400, 
        "ok":false, 
        "statusText":"Bad Request", 
        "type":2 
    }; 
    
  2. 解析內JSON和使用它...

    var err = JSON.parse(message._body); 
    console.log(err.error);