Decode http response in Angular - JSON.parse issue - json

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.

Related

Typescript HttpClient.post returning bad request from json formatted string

Ok I have been manipulating this string for hours! So any help is greatly appreciated
I am trying to simply make a post call and generate a password. The api is setup to take in a string a parses the json formatted string itself.
private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
constructor(http: HttpClient) {
var url: string = 'https://eus-safeaccounts-test.azurewebsites.net/' + 'passwords/generate';
var body: string = '"{\"regex\":\"[a-zA-Z0-9]\",\"minLength\":8,\"maxLength\":12}"';
http.post<string>(url, body, { headers: this.headers }).subscribe(result => {
this.signUpResponseStr = result["password"];
}, error => console.error(error));
}
This call returns code 400 bad request. (I think because the text is not being seen as json?)
However, if we set body = '""'; then we get a password sent back from the api no problem. It is seen as an empty string on API side and then they give us a password. Exploring further I tried setting body = '"abc"'; because that is a string not following json format. In this case, we DO NOT get bad request 400, but the api recognizes bad json format and returns Invalid Json
My Question:
What should the body string look like for me to send this request? The API is open so anyone can reproduce and the API code shouldn't have anything to do with the 400 bad request issue, as we can see from my explorations, but the code is here https://github.com/nickpavini/SafeAccountsAPI.
Thanks for any help! :)
EDIT: I also tried sending as JSON type and I also tried JSON.stringify() with no luck
Found it. The string is a bit tricky to understand but hopefully this will help others.
body = '"{\\"regex\\":\\"[a-zA-Z0-9]\\",\\"minLength\\":8,\\"maxLength\\":12}"'
In this case it seems that the body contains a string. (the actual string that will be received by the server)
Inside that string, whenever we need the server to see a " that does not close the string, we must pass an actual backslash \\ and then a ". We do not need 3 backslashes in this case because the single quote ' at the beginning makes sure all paranthesis are included.
Note: Test this with the api in question if it seems weird to you. I think it has to do with the api implementation.
Probably body should not be double quoted, and should look instead like...
var body: string = '{"regex":"[a-zA-Z0-9]","minLength":8,"maxLength":12}'

API Response returns Mappable Object in iOS but Json on Android

I'm a newbie on mobile development and React-Native, this might come across as a very mundane thing to some of you, but I'm making an Api call and then mapping the results to create the same component but with different data.
This works fine on Iphone but on Android it does not.
The response from the req is an Object for both devices but on Android, it seems to be a json object that I simply cannot map with or use on a Flatlist.
I've tried JSON.parse to get the json object to a js object but it simply doesn't, like it. It throws out an unexpected token error.
I've attached a log for the Android object first and the same object for iPhone (Already mappable and a JS object).
Can someone tell me why this happens? I'd very much appreciate it!
enter image description here
____________________ After Changing to Fetch _______________________
Hey, I changed from Axios to fetch and now I get an unhandled promise warning saying 'Unhandled promise rejection: SyntaxError: JSON Parse error: Unrecognized token '' '.
Don't think I'm doing anything wrong here...
Well ... your response-object gets truncated due to memory issues on your real-device ... most likely your response object is kinda large ...
And that's just the way axios fetch response-data ... through chunks, you just get a slice of the response...
I came across this issue before ... and the solution was to switch to fetch
Edit
try {
const rawResponse = await fetch(...);
const text = await rawResponse.text();
console.log(text);
const parsedRes = JSON.parse(text);
console.log('parsedRes', parsedRes);
} catch(error) {
console.log('fetch error', error);
}

Uncaught Reference Error: Jsonbody is not defined at Request.request

I am trying to show details of an api call in my electron app. this is the api and sample json data:
[
{
ID: 596,
title: "Carolyn Wood",
content: "<p>Turning away bad clients can leave you feeling oddly guilty. They’re sort of like alcoholic or meth head cousins who force you, by their own bad behavior into denying them things you wouldn’t deny other people. You’re left feeling not quite yourself. </p> ",
link: "https://quotesondesign.com/carolyn-wood/",
custom_meta: {
Source: "Twitter"
}
}
]
I am using request module to fetch data and JSON.parse(body) to get the object like below:
let request = require('request');
request("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
(err, response, body)=>{
let jsonBody = JSON.parse(body);
let randQuote = jsonBody[0]["content"];
document.getElementById("quote").innerHTML = randQuote;
});
In console, I get this error:
Uncaught ReferenceError: jsonBody is not defined
at Request.request [as _callback] (D:\ElectronDev\ElectronBasics\quote-widget\index.js:8
pointing on this line JSON.parse(body). How do I resolve this?
The response from the endpoint has some extra characters at the start of the response and that's the reason the JSON.parse can not parse it into object and jsonBody is undefined.
Here is the fix to your specific response for this. Change your line of code to this.
let jsonBody = JSON.parse(body.substring("/**/mycallback(".length, body.length - 1));
Hope this helps.

JSON.parse returning undefined object

Blizzard just shut down their old API, and made a change so you need an apikey. I changed the URL to the new api, and added the API key. I know that the URL is valid.
var toonJSON = UrlFetchApp.fetch("eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items,statistics,progression,talents,audit&apikey="+apiKey, {muteHttpExceptions: true})
var toon = JSON.parse(toonJSON.getContentText())
JSON.pase returns just an empty object
return toon.toSorce() // retuned ({})
I used alot of time to see if i could find the problem. have come up empty. Think it has something to do with the "responce headers".
Responce headers: http://pastebin.com/t30giRK1 (i got them from dev.battle.net (blizzards api site)
JSON: http://pastebin.com/CPam4syG
I think it is the code you're using.
I was able to Parse it by opening the raw url of your pastebin JSON http://pastebin.com/raw/CPam4syG
And using the following code
var text = document.getElementsByTagName('pre')[0].innerHTML;
var parse = JSON.parse(text);
So to conclude I think it is the UrlFetchApp.fetch that's returning {}
So i found the problems:
I needed https:// in the URL since i found after some hours that i had an SSL error
If you just use toString instead of getContentText it works. Thow why getContentText do not work, i am not sure of.
was same problem, this works for me (dont forget to paste your key)
var toonJSON = UrlFetchApp.fetch("https://eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items%2Cstatistics%2Cprogression%2Caudit&locale=en_GB&apikey= ... ")

apigee 127 - JSON is escaped when ran in mock mode

I'm guessing I've missed something silly so I apologize in advance.
I'm trying to run the example found at the following URL in mock mode: https://github.com/apigee-127/a127-samples/blob/master/weather-basic/api/swagger/swagger.yaml
The JSON response looks like it's being escaped and it's causing the response validator to fail:
{
"message": "Response validation failed: invalid content type (text/plain). These are valid: application/json",
"failedValidation": true,
"originalResponse": "{\"base\":\"Sample text\",\"clouds\":{\"all\":1},\"cod\":1,\"coord\":{\"lat\":1,\"lon\":1},\"dt\":1,\"id\":1,\"main\":{\"humidity\":1,\"pressure\":1,\"temp_max\":1,\"temp_min\":1,\"temp\":1},\"name\":\"Sample text\",\"sys\":{\"country\":\"Sample text\",\"id\":1,\"message\":1,\"sunrise\":1,\"sunset\":1,\"type\":1},\"weather\":[{\"description\":\"Sample text\",\"icon\":\"Sample text\",\"id\":1,\"main\":\"Sample text\"}],\"wind\":{\"deg\":1,\"speed\":1}}"
}
Any ideas would be awesome!
You need to send something like this res.json({});
Send as json object don't stringify your result object ,
var result = {name:"asdf",id:1212}
res.json(result);