How to get more data with axios? - javascript

when I do this:
const uuidapi = await axios.get('https://api.hypixel.net/player?key=mykey&name=' + args[1]);
console.log(uuidapi);
I get this response from Axios:
https://paste.menudocs.org/paste/7vppu
So my question is: How do I get the Data after "socialMedia"? Heres how socialMedia looks like:
"socialMedia": {
"links": {
"YOUTUBE": "https://www.youtube.com/channel/UC1L7H9qQyB2zZgt-1XUv6jA",
"DISCORD": "Altpapier#4847"
}
}
Why does it say socialMedia: [Object], and how do I get more than this?
I can't use const { data } = await axios.get(URL); because I want to get 2 URL responses with the complete data.
I also want to be able to safe for example the DISCORD Name Altpapier#4847 how do I do that?

All the data is already here, it's just the formatting of console.log that's not printing every nested object.
If you replace
console.log(uuidapi);
by
console.log(JSON.stringify(uuidapi));
it will work better

See this question: How can I get the full object in Node.js's console.log(), rather than '[Object]'?
you can use console.dir( yourObject, { depth: null } )

Related

How to use JSON response as an array in javascript

Here is my response I get from API request:
[ 'bookShelf3', 'bookShelf4', 'bookShelf5' ]
Here is a part of my code which searches through my mongoDB Databese:
const responseToSearchC = (req, res) => {
console.log(req.body.searchTerm);
db.collection('subtitle')
.find({
series: { $in: ['bookShelf1'] },
$text: { $search: req.body.searchTerm },
})
I just want to make my code dynamic and instead hard coding ['bookShelf1']
set its value by JSON response.
the problem is the response from API is an object (although it is look like an array) and I cannot replace it with my hard codded array ['bookShelf1']
I tried to stringify it but it didn't work cuz its a string again, and not an array like hardcoded one
If the response is really an object like:
{ 0: 'bookShelf3', 1:'bookShelf4', 2: 'bookShelf5'}
you can simply utilize the Object.values() method which returns all of the object's values as an array.
Here's an example:
let ob={ 0: 'bookShelf3', 1:'bookShelf4', 2: 'bookShelf5'};
console.log(Object.values(ob));

passing in json variable into sendgrid's dynamic_template_data

I'm having some trouble passing into a variable that holds a json object into sendgrid's dynamic_template_data. My setup looks like this:
const send = async (address, mentions) => {
console.log('mentions json obj', mentions)
let name = "john"
try {
let config = {
headers: {
Authorization: `Bearer ${process.env.sendgridKey}`,
}
}
let data = {
personalizations: [
{
to: [
{
email: `${address}`,
},
],
dynamic_template_data: {
name: name,
allMentions: mentions
}
}
],
from: {
email: "email#email.com",
name: "Mentionscrawler Team"
},
template_id: process.env.template_id,
}
await axios.post("https://api.sendgrid.com/v3/mail/send", data, config)
} catch (error) {
console.error(error, 'failing here>>>>>>>')
}
}
when I console.log mentions, which is json, and paste the code I get from the terminal directly into the allMentions key, it works. but when I just pass in mentions itself, nothing shows up on the sent email. I've been very confused the last few hours why this is happening. Any advice appreciated.
edit: i should also note that allmentions is an object with keys that hold arrays. So I'm looking to iterate over those arrays. Again, this totally all works if I just paste in directly what mentions is, but passing in mentions is giving me an issue.
Thank you very much,
just realized what was wrong. sendgrid's template requires a json object, so I assumed that I needed to use json.stringify on my mentions obj. Turns out I didn't need to do that, as long as all values are in string format.

How can I accesss to the elements of array objects?

How Can I get data from this json data ?
I get this data from the server, and it sends some database's datas by using sequelize.
Data what I want to access is
{result: "[{"userid":"a","speed":10},{"userid":"b","speed":20},{"userid":"c","speed":30}]"}]" }
And I tried console.log(result[0].userid);
But, I only got errer like this. ' Uncaught TypeError: Cannot read property 'userid' of undefined'.
Could you tell me what I have to fix?
You gave an invalid JSON, the json should be something like this:
Formatted JSON Data
{
"result":[
{
"userid":"a",
"speed":10
},
{
"userid":"b",
"speed":20
},
{
"userid":"c",
"speed":30
}
]
}
And after that you can access it:
const json = {
"result":[
{
"userid":"a",
"speed":10
},
{
"userid":"b",
"speed":20
},
{
"userid":"c",
"speed":30
}
]
};
console.log(json.result[0].userid);
Your JSON is badly formatted.
Try this instead...
{"result":[{"userid":"a","speed":10},{"userid":"b","speed":20},{"userid":"c","speed":30}]}
The main issues were...
{result: "[{"userid"
Should be...
{"result":[{"userid"
And
"speed":30}]"}]" }
Should be...
"speed":30}]}
Please note, the whitespace between the items makes no difference, but I have remove to reduce the size of the JSON string

How to acces to specific properties into a JSON or Object in JavaScript

I'm making an app in Nodejs using express and node-xlsx module, what I want to do is to make the user able to upload an xlsx file (which has to have an specific format of two columns), an then the server reads it and does something with each row of the file.
(Example of my test file, being the columns A and B respectively):
Johny Wilson | jonhny#email.com
Andrew Jehnsen | andrew#example.com
Billy Soon | billy#mail.com
In order to do this, I've decided to use the node-xlsx module, which, after reading the file with this code:
var xlsx = require('node-xlsx');
router.post('/enviar', upload.single("lista"),(req, res, next) =>{
//dir is the path of the xlsx file
const workSheetsFromFile = xlsx.parse(dir);
res.send(workSheetsFromFile);
});
returns an object that looks like this:
[
{
"name": "Hoja1",
"data": [
[
"Johny Wilson",
"jonhny#email.com"
],
[
"Andrew Jehnsen",
"andrew#example.com"
],
[
"Billy Soon",
"billy#mail.com"
]
]
}
]
As you can see, the module returns the data of all the file, including the sheet's details (In this case only one), I want to access only to the 'data' array which contains keys and values to process them.
I've already tried to loop on the data array with:
workSheetsFromFile.data.forEach((element) =>{
console.log(element);
});
and
workSheetsFromFile[data].forEach((element) =>{
console.log(element);
});
and
workSheetsFromFile['data'].forEach((element) =>{
console.log(element);
});
but all of them just send me an error like "Cannot read property 'forEach' of undefined" or "data is not defined" :(
For now, with those few lines of code I was specting to iterate the data array and print each pair of key and value, so once that is fixed, inside this loop process each key and value in order to send automated mails.
What you have here seems to be an array of objects, not an object itself!
try
workSheetsFromFile[0].data.forEach((element) => {
console.log(element);
});
If you have more elements, consider first looping the array and then extracting data
const structuredData = workSheetsFromFile[0].data.map(res => {
return res
});
workSheetsFromFile.forEach(sheet => {
//access data
console.log(sheet.data)
//or
sheet.data.forEach(data => {
//access each data
console.log(data)
})
})

How to push response from axios.all to a vue data element?

I am using axios.all to do asynchronous calls to the YouTube API.
My code is:
export default {
data () {
return {
cats: [],
dogs: [],
catsAndDogs: []
}
},
methods: {
search: function (){
var that = this
axios.all([
axios.get('https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=25&q=cats&key=API_KEY'),
axios.get('https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=25&q=dogs&key=API_KEY')
])
.then(axios.spread(function (catsRes, dogsRes) {
that.cats = catsRes
that.dogs = dogsRes
console.log(catsRes)
console.log(dogsRes)
}))
}
}
}
This is as far as I can get because when I try to put the response from axios.spread (catsRes or dogsRes) into the arrays, they end up empty.
However if I comment out 'that.cats = catsRes' and 'that.dogs = dogsRes' the console prints out the response fine.
Can someone tell me why this is not working?
Ideally I would like to have an array for just the cat videos, an array for the dog videos and an array with both cats and dogs.
* EDIT *
Top is the console response when I try to put the GET request data into the data element and bottom is the console response when I don't try to put the GET request data into the data element:
https://imgur.com/a/NY1nc
The axios response is an object with some additional information about the response. To get the actual response JSON data, use the response object's data property. Furthermore, it seems like the YouTube response puts the actual results in an items property, so use that too:
async search () {
const [cats, dogs] = await axios.all([
axios.get('...cats url...'),
axios.get('...dogs url...'),
]);
this.cats = cats.data.items;
this.dogs = dogs.data.items;
}

Categories

Resources