I just want to console.log two properties of a json return from an api call. I've never used the request library. When I try to loop through body it just returns strings and I can see the line carriages. With axios I made the call and looped through it with no problem...
I tried using a for, forin, and object entries. I don't understand the output.
const request = require("request");
async function GetPosts() {
await request("https://jsonplaceholder.typicode.com/posts", function (error, response, body) {
for (const key in body) {
if (body.hasOwnProperty(key)) {
const element = body[key];
console.log(element);
}
}
});
}
GetPosts();
I just want to print title and body properties from the json result.
You need to call JSON.parse()
to parse the response body into an object.
Then when you loop over the elements of the array, you should just print the properties you want, not the whole object.
const request = require("request");
async function GetPosts() {
await request("https://jsonplaceholder.typicode.com/posts", function (error, response, body) {
body = JSON.parse(body);
body.forEach(item => {
console.log(item.title, item.body);
});
});
}
GetPosts();