Root SL
Root SL

Reputation: 69

How to read json response from node js server?

I have a NodeJS REST API. In that API, I have to call another 3rd party API to get some data. It gives us data as JSON. This is how I set that response of data to my REST url response.

request('http://dev.demo.com/api/v1/wow/getFreeviewLoginAndCallAPI/123', function (error, response, body) {
if (!error && response.statusCode == 200) {
    console.log(body);
    res.json(body);
}

});

And then I get a response like this.

"{\"Response\":{\"@attributes\":{\"Package\":\"MONTHLY\",\"Surname\":\"Taylor\",\"CSN\":\"104801\",\"Email\":\"[email protected]\",\"MiscInformation\":\"\",\"Message\":\"CUSTOMER_ACTIVE\"}},\"Submission\":{\"@attributes\":{\"SubmitterRef\":\"0778798654\",\"Submitter\":\"demoName\"}}}"

But when I use that 3rd party URL in my browser , I get a clean and nice JSON output. Like the following.

(without \ symbol)

No other "\" symbols and it's clean. What I need to do is I need to access some values of this response. In the node js. I need to send the response as follows.

res.json(body.Response);

But it's null. And also I need to take all these values to variables. How can I do that ?

Upvotes: 0

Views: 9791

Answers (1)

Sumeet Kumar Yadav
Sumeet Kumar Yadav

Reputation: 12945

The response from you third part api is as string , you probably need to parse before sending to client .

request('http://dev.demo.com/api/v1/wow/getFreeviewLoginAndCallAPI/123', function (error, response, body) {
if (!error && response.statusCode == 200) {        
    res.json( JSON.parse(body));
}});

You can not use body.Response directly because its string not object,firstly parse it and then send to client ,like

var json = JSON.parse(body); 
res.json(json.Response);

Upvotes: 1

Related Questions