How to get object array generated by axios get - javascript

(async() =>{
const axios= require('axios');
const response = await axios("https://graph.facebook.com/v13.0/110524034851999/feed?limit=3&access_token=×××××××");
const data = response.data;
console.log(data);
console.log(data[0]);
})();
Above is the code I am using to get json from Facebook API I am getting an object as below
data: [
{
created_time: '2022-04-14T14:01:45+0000',
message: 'How to make jw',
id: '...'
},
{
created_time: '2022-04-14T14:01:19+0000',
message: 'Testing',
id: '....'
},
{
created_time: '2022-04-14T01:51:41+0000',
message: 'Enriqueta',
id: '.....'
}
],
I am not able to get the data from object using data[0] which should return me first object but it's giving me undefined error how can I get the message which is on first array of data object from the above json?

replace
console.log(data[0]);
with
console.log(data.data[0]);
maybe?

Related

How to replace a object inside JSON array with a fetch

I have a JSON that looks like this:
[{
is_email_opt_in: false,
credit_card_type: 'visa',
order_source: 'www',
channel_id: 1,
external_source: '',
products: {
url: 'https://api.bigcommerce.com/stores/XXX/v2/orders/149/products',
resource: '/orders/149/products'
}
}]
I'm trying to replace all "products" fields with the a fetch result that comes from BigCommerce API based on the value of the products.resource key.
This is my current code:
result = await this.instanceV2.get(`/orders`);
if (result)
result.forEach(
async (order) =>
(order.products = await this.instanceV2.get(
order.products.resource
))
);
But it's not working, the field doesn't get replaced.

Response.data how to get a single data value

Here is the code that im using to try get a single element out of the data.response of an api:
client.on("message", msg => {
var axios = require("axios").default;
var options = {
method: 'GET',
url: 'https://dad-jokes.p.rapidapi.com/random/joke',
headers: {
'X-RapidAPI-Host': 'dad-jokes.p.rapidapi.com',
'X-RapidAPI-Key': '0f787e5af5msh468814e0b585173p1cacafjsn7d774dfb44ff'
}
};
if(msg.content === "daddy"){
axios.request(options).then(function (response) {
console.log(response.data);
let dataDad = response.body
msg.channel.send(`${dataDad}`)
})`
and here is the response that i get from the api:
{
success: true,
body: [
{
_id: '60dd3729df8a37528bc79b03',
setup: 'How often do scientists check the table of elements?',
punchline: 'Periodically',
type: 'periodical',
likes: [],
author: [Object],
approved: true,
date: 1618108661,
NSFW: false
}
]
}
How do I use the "setup" from the response data in my code at msg.channel.send( "the "setup" ) ?
I believe, You need to do response.data.body[0].setup in order to get the first objects setup property
msg.channel.send(response.data.body[0].setup);
response.data.body is an array of objects. So, if you want to access the first object in that array, you would use response.data.body[0] So, to get the .setup property from that object, you would use this:
msg.channel.send(response.data.body[0].setup);
That will get you the setup property from the first object in the response.data.body array.

How to retrieve specific value from list of Json Object in NodeJS

I'm trying the below code to retrieve the executionArn but I'm getting this error
Error [SyntaxError]: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
How to get executionArn or stateMachineArn from each record? Any help would be much appreciated.
console.log(data) - Output
{
executions: [
{
executionArn: 'arn:aws:states:us-east-2:12222:execution:test:dcb689bc',
stateMachineArn: 'arn:aws:states:us-east-2:12222:stateMachine:test-sm',
name: 'test-name',
status: 'SUCCEEDED',
startDate: 2021-06-17T13:43:39.817Z,
stopDate: 2021-06-17T13:43:53.667Z
},
{
executionArn: 'arn:aws:states:us-east-2:12222:execution:test:sd32dsdf',
stateMachineArn: 'arn:aws:states:us-east-2:12222:stateMachine:test-sm',
name: 'test-name1',
status: 'SUCCEEDED',
startDate: 2021-06-17T13:43:39.817Z,
stopDate: 2021-06-17T13:43:53.667Z
}
],
nextToken: 'aadfdfdf'
}
Code:
stepfunctions.listExecutions(params, function(err, data) {
if (err) console.log(err, err.stack);
else
console.log(data)
//console.log(data.executions[0].executionArn)
data = JSON.parse(data);
data.forEach(function(result) {
var arnValue = result.executions.executionArn;
console.log(arnValue);
});
});
data is an object and executions inside it is an array, so try this
data.executions.foreach(function (execution) {
console.log('executionArn', execution.executionArn)
console.log('stateMachineArn', execution.stateMachineArn)
})
executions.map(e=>{
// access it here
let a = e.executionArn;
});
The provided output (data) is not a valid JSON object,
{...
startDate: 2021-06-17T13:43:39.817Z,
stopDate: 2021-06-17T13:43:53.667Z
}
For valid JSON, it should look like
{...
"startDate": "2021-06-17T13:43:39.817Z",
"stopDate": "2021-06-17T13:43:53.667Z"
}
for it to be iterated correctly.
If the data is from the server (API), stringify the dates before returning them, and the values could be found by
data.executions.map(execution=>{
let arnValue = execution.executionArn;
console.log(arnValue);
})

Parsing a JSON Stringified variable returns the value undefined?

The code below is the entirety of my discord.js message event, I am using discord.js as well as node-wit. When wit identifies a message including a math expression, it will evaluate the value and send it back to the user.
It sends back data using JSON.stringify(). However when I try and parse it, everything I log only returns undefined.
client.on('message', (message) => {
wClient
.message(message.content, {})
.then((data) => {
const response = JSON.stringify(data, ['intents', 'name', 'confidence']);
const responseParsed = JSON.parse(response);
console.log(response);
console.log(responseParsed);
if (responseParsed.name == 'Math') {
message.channel.send(eval(data));
}
})
.catch(console.error);
});
The actual response of the console logs for the JSON.stringify() and then the JSON.parse() are listed below:
JSON.Stringify()
{"intents":[{"name":"Math","confidence":0.9945}]}
JSON.parse()
{ intents: [ { name: 'Math', confidence: 0.9945 } ] }
based on this structure
{ intents: [ { name: 'Math', confidence: 0.9945 } ] }
I assume that this is how it should be
to try
if (responseParsed.intents[0].name == 'Math') {
message.channel.send(eval(data));
}

res.json() sends data in the form of res.data but accessing _id within it is undefined

I'm having trouble understanding why a res.json call in my app sends data (an order object) but when I try accessing a piece of that data (res.data._id) and storing it into a variable I get it as undefined. I know this piece of data exists since the console.log shows the order object's _id value but console.logging that particular piece returns undefined. What causes this behavior?
Backend logic:
router.post("/new", function(req, res) {
const productInfo = req.body.productInfo;
let order = new Order();
order.product = {
_id: productInfo.id,
name: productInfo.name,
description: productInfo.description,
price: productInfo.price,
quantity: productInfo.quantity
}
order.status = "Created";
order.total = productInfo.price * productInfo.quantity;
order.owner = {
id: req.body.id,
username: req.body.username
}
order.save().then(order => {
res.status(200).json(`Order created successfully! Created order details: ${order}`);
}).catch(err => {
console.log("Order create error: ", err.message);
});
});
Frontend logic:
let orderID = "";
return (
<PayPalButton
createOrder={(data, actions) => {
axios.post("http://localhost:4000/orders/new",
{productInfo, userID, username}
).then((res) => {
if(res.status === 200) {
console.log(res.data);
console.log(res.data._id)
orderID = res.data._id;
}
}).catch((err) => {
console.log(err);
});
return actions.order.create({
purchase_units: [{
amount: {
currency_code: "USD",
value: props.amount
}
}]
})
}}
/>
)
console.log response:
Order created successfully! Created order details: { product:
{ _id: '5e68330c8dcfa56868f1d23a',
name: 'Birdhouse',
description: 'A beautiful birdhouse',
price: 5,
quantity: 2 },
owner: { username: 'tgoandrex' },
createdAt: 2020-04-12T23:04:46.286Z,
_id: 5e93a16eb1cbc837d80167ef,
status: 'Created',
total: 10,
__v: 0 }
undefined
axios is expecting the endpoint to return a JSON object, but you're sending a string to the client:
res.status(200).json(`Order created successfully! Created order details: ${order}`);
Attempting to access res.data on the client will give you the string literal
"Order created successfully! Created order details: [elided]"
But because this is a string, the property _id does not exist on it, and so it will return undefined.
In order for this to work, you need to send just the object, rather than a string:
res.status(200).json(order);
Your /orders/new endpoint doesn't respond with JSON but with a simple string. Express's Response#json method is expecting an object that will be serialized to JSON, not a string.
You should just pass your order as single argument to the json method:
res.status(200).json(order);
otherwise, your React app won't be able to parse the JSON since it isn't a valid JSON format.

Categories

Resources