4

I am getting the JSON error response from server in the following way,

let err = {
        "_body": "{\"error\":\"264\",\"message\":\"Please enter valid usename/password\",\"object\":null}",
        "status": 400,
        "ok": false
    }

And i want to display the error message on the screen 'Please enter valid usename/password'

I tried in the following way but no luck,

console.log((this.err._body).replace(/\\/g, ''));
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
vishnu
  • 4,377
  • 15
  • 52
  • 89
  • Possible duplicate of [Safely turning a JSON string into an object](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – Liam Oct 18 '16 at 13:31

2 Answers2

9

You just need to deserialize the body.

let err = {
        "_body": "{\"error\":\"264\",\"message\":\"Please enter valid usename/password\",\"object\":null}",
        "status": 400,
        "ok": false
    }

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

Click on Run code snippet to see this working.

Martin
  • 15,820
  • 4
  • 47
  • 56
4

You probably need to decode the wrapped json string again:

let responseBody = JSON.parse(this.err._body);
console.log(responseBody.message);
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71