简体   繁体   中英

Decode http response in Angular - JSON.parse issue

After quite a bit of messing around, I've got to the point where I can recieve the following body in a 404 error response from my backend. I'm struggling to parse the content into angular so I can use it. I'm know this is simple stuff, so sorry to ask such a basic question. The _body looks like this.

 _body: "{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}"

These are fine:

console.log("Err = ", err);
Err =  Response {_body: " 
{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}", status: 404, ok: false, statusText: "OK", headers: Headers, …}

and:

console.log("Err Body : ", err._body);
Err Body :  
{\"httpStatus\":404,\"errorType\":\"NotFound\",\"message\":\"Device does not exist!\"}

But this doesn't work:

let errorObject = eval(errorString);
Uncaught (in promise): SyntaxError: Invalid or unexpected token

...

var errBody = JSON.parse(errorString);
console.log("JS err body", errBody);
Error: Uncaught (in promise): SyntaxError: Unexpected token \ in JSON at position 1

But I can't figure out how to get the individual fields out. I'm aware that the above efforts are naive and wrong. I'm sure anyone with JS or angular skills can solve this in a minute.

PS cut me some slack. I'm a hardware designer. I'm here because I don't know something, which is always the best reason to ask a question.

Edit:

Thanks for the answers. JSON.parse does not work for me!?

SyntaxError: Unexpected token \ in JSON at position 1

I looked more closely at what you had success with, and I agree it works fine in the console. But it does not work for me in Angular. What did work was:

let errBody = JSON.parse("\"" + err._body + "\"");

Although it seems ridiculous to do. Especially since, afterwards, the result is not quite right:

err body {"httpStatus":404,"errorType":"NotFound","message":"Device does not exist!"}

If I then try to get at errBody.message, it's undefined!... This is totally absurd. What am I doing wrong? How do you guys do this for a living? It's killing me!

I'm assuming errorString is err._body ? Either way, parsing that string to JSON should be as simple as:

let error = JSON.parse(err._body);

I came back to this recently. And finally managed to figure it out. I needed to remove some unwanted backslashes in the body before trying JSON Parse.

const errorStringReplaced = err._body.replace(/\\/g, '');
const errBody = JSON.parse(errorStringReplaced);
this.outcomeMessage = errBody.message;

Having done that, I could then grab the innards properly. I'd still prefer to send the object properly in the first place, but this will have to do for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM