json api parse object - javascript

Good day, I'm trying to get certain values ​​​​with api the maximum that I can do is output all the json
const api_url = 'https://api.battlemetrics.com/servers/3753675'
async function getData() {
const response = await fetch(api_url);
const json = await response.json();
const { data } = json;
console.log(data)
}
getData();
please could tell me how to get the element, I tried like this:
const api_url = 'https://api.battlemetrics.com/servers/3753675'
async function getData() {
const response = await fetch(api_url);
const json = await response.json();
const { name, id, status } = json;
console.log(name, id, status)
}
getData();
but i get "undefined undefined undefined"
The object I asked for:
{"data":{"type":"server","id":"3753675","attributes":{"id":"3753675","name":"Rusticated.com Sandbox - Creative | Minigames | Bedwars\r","address":null,"ip":"199.231.233.240","port":28015,"players":201,"maxPlayers":1000,"rank":1,"location":[-87.618889,41.875744],"status":"online","details":{"official":false,"rust_type":"modded","map":"BuildBattleArenaScrimGames","environment":"w","rust_ent_cnt_i":0,"rust_fps":43680,"rust_fps_avg":43680,"rust_gc_cl":null,"rust_gc_mb":null,"rust_hash":"","rust_headerimage":"https://cdn.discordapp.com/attachments/811789078105554984/832668733184671754/Rusticated_Mini_Games_Banner_512x256.png","rust_mem_pv":null,"rust_mem_ws":null,"pve":false,"rust_uptime":null,"rust_url":"https://rustminigames.com","rust_world_seed":1337,"rust_world_size":null,"rust_description":"Rusticated Minigames Beta \n Bedwars \n Creative \n GunGame \n Targets \n More Coming Soon...","rust_modded":true,"rust_queued_players":0,"rust_born":"2022-06-05T00:00:00.000Z","rust_last_ent_drop":"2021-08-06T00:10:18.261Z","rust_last_seed_change":"2020-09-03T18:33:52.047Z","rust_last_wipe":"2021-08-06T00:10:18.261Z","rust_last_wipe_ent":29035,"serverSteamId":"90159726978107400"},"private":false,"createdAt":"2019-06-18T18:35:26.890Z","updatedAt":"2022-06-06T10:05:57.516Z","portQuery":28038,"country":"US","queryStatus":"valid"},"relationships":{"game":{"data":{"type":"game","id":"rust"}}}},"included":[]}

If you want to get object you said, try this.
const API_URL = 'https://api.battlemetrics.com/servers/3753675';
async function getData() {
const response = await fetch(API_URL);
const json = await response.json();
console.log(json); // you need to check json first. (*)
}
getData();
Then you can use destructuring.
const API_URL = 'https://api.battlemetrics.com/servers/3753675';
async function getData() {
const response = await fetch(API_URL);
const json = await response.json();
const { name, id, status } = json.data.attributes; // (*)
console.log(name, id, status);
}
getData();

You just need to replace:
const { name, id, status } = json;
with:
const {
data: {
id,
attributes: { name, status }
}
} = json;
because your keys are not directly into the response, but nested.

Related

React Native how to get only some data from api

Given url Data==> need to get only Karnataka state details
[{"id":1,"title":"TELANGANA","image":"url","stateCode":"TS"},{"id":4,"title":"TAMILNADU","image":"url","stateCode":"TN"},{"id":3,"title":"KARNATAKA","image":"url","stateCode":"KN"},{"id":2,"title":"ANDHRA","image":"url","stateCode":"AP"}]
Here code to get data===>
const [states, setStates] = useState([]);
useEffect(() => {
handleGetStates()
}, []);
const handleGetStates = async () => {
let values = {
url: `url`,
method: 'get',
}
try {
const response = await axios(values)
setStates(response.data)
console.log(response.data,'response');
} catch (error) {
// handle error
console.log(error);
}
};
You can filter on the array returned from the API:
...
const response = await axios( values );
setStates( response.data.filter(state => state.title === 'KARNATAKA' );
// result: [ {"id":3,"title":"KARNATAKA","image":"url","stateCode":"KN"} ]
...
This will loop through the response and only keep states that have a title of "KARNATAKA"
You can use an array filter method
const {data} = await axios(values);
const result = data?.filter(el=>el.stateCode==='KN')

json filtering javascript api

Hello i have some problem with json filtration
when i print jsonArray without id (jsonArray) prints the object to me normally but when i add .id (jsonArray.id) its says undefined What am I doing wrong?
the object i gets with jsonArray and i want to print only 'id' of it
{id: 39497866969165, product_id: 6677529493581, title: '8', price: '181.50'}
const api_url= 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json'
async function getID() {
const response = await fetch(api_url);
const data = await response.json();
const findsize = data.product.variants
const jsonArray = findsize.filter(function(ele){
return ele.title == "8";
});
console.log(jsonArray.id)
}
getID();
jsonArray is array not object. And getID is a async function. It will return promise. You need to call then to get result.
const api_url = 'https://eu.kith.com/collections/kith-mlb-for-clarks-originals/products/ck26166616.json'
async function getID() {
const response = await fetch(api_url);
const data = await response.json();
const findsize = data.product.variants
const jsonArray = findsize.filter(function(ele) {
return ele.title == "8";
});
const tmp_obj = {
id: jsonArray[0].id,
product_id: jsonArray[0].product_id,
title: jsonArray[0].title,
price: jsonArray[0].price
}
//console.log(tmp_obj)
return tmp_obj
}
getID().then(result => console.log(result));
It's because jsonArray here is a list and not a single object.
First check it's length to make sure there's atleast one object after the filter and log the first element via:
if (jsonArray.length > 0) {
console.log(jsonArray[0].id)
}

How can I get my mongoose collection data displayed on the client side?

I am trying to fetch the data from my mongoose collection, and dispaly that data on client side. But I am getting 'Object' on the cilent side instead of data, but the data is saved in the database.
Can anyone help me, Thanks
This is my code
router.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Library', { useNewUrlParser: true });
const api_list = new mongoose.Schema({
data:Array
});
const api = mongoose.model('api_listLs', api_list);
router.post('/api/list/Post', (request, response) => {
const data = request.body
const apiList = new api({data:data});
apiList.save().then(() => {
console.log(data)
response.json(data);
}).catch(() => {
response.status(400).send("Item was not send to the database")
});
});
router.get('/api/list/Get', (request, response) => {
api.find({},(err,data)=> {
if(err){
response.end();
return;
}
response.json(data);
});
});
page1.js
I used a fetch 'POST' method to pass data into database. And save it in a collection
function TableRow() {
let items = 'hey'
let domore = 'hi'
let cells = document.querySelectorAll('#recieve-info td');
cells.forEach(cell => cell.onclick = async function () {
let prevcell = cell.previousElementSibling;
if (prevcell) {
let data = {items, domore}
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
const response = await fetch('/api/list', options);
const json = await response.json();
console.log(json);
}
});
}
page2.js
Here I used fetch 'GET' method to to retreive data from database and show it on client side
async function ParaG() {
const response = await fetch('/api/list');
const data = await response.json();
console.log(data);
alert(data);
for (item of data) {
const para = document.querySelector('.Second-Para');
para.innerHTML += `${item.data}, ${item.data}`
}
}
'.Second-Para' is a p element in a container 'div'
Here is the output. I am getting 'Object' instead of data
This app pass data from one page to another by onclick
result is in data key and data is array of objects so use {data} to access the data like this:
async function ParaG() {
const response = await fetch('/api/list');
const {data} = await response.json();
console.log(data);
alert(data);
for (item of data) {
let info = item.data[0];//access to data
const para = document.querySelector('.Second-Para');
para.innerHTML += `${info.items}, ${info.domore}`
}
}

How to make promise to wait for all objects to be complete and then push to array?

The getURL() function creates an array of scraped URLs from the original URL. getSubURL() then loops through that array and scrapes all of those pages' URLs. Currently, this code outputs just fine to the console, but I don't know how to wait for my data to resolve so I can push all gathered data to a single array. Currently, when I try and return sites and then push to array, it only pushes the last value. I believe it's a promise.all(map) situation, but I don't know how to write one correctly without getting an error. Ideally, my completed scrape could be called in another function. Please take a look if you can
const cheerio = require('cheerio');
const axios = require('axios');
let URL = 'https://toscrape.com';
const getURLS = async () => {
try {
const res = await axios.get(URL);
const data = res.data;
const $ = cheerio.load(data);
const urlQueue = [];
$("a[href^='http']").each((i, elem) => {
const link = $(elem).attr('href');
if (urlQueue.indexOf(link) === -1) {
urlQueue.push(link);
}
});
return urlQueue;
} catch (err) {
console.log(`Error fetching and parsing data: `, err);
}
};
const getSubURLs = async () => {
let urls = await getURLS();
try {
//loop through each url in array
for (const url of urls) {
//fetch all html from the current url
const res = await axios.get(url);
const data = res.data;
const $ = cheerio.load(data);
//create object and push that url into that object
let sites = {};
sites.url = url;
let links = [];
//scrape all links and save in links array
$("a[href^='/']").each((i, elem) => {
const link = $(elem).attr('href');
if (links.indexOf(link) === -1) {
links.push(link);
}
//save scraped data in object
sites.links = links;
});
// returns list of {url:'url', links:[link1,link2,link3]}
console.log(sites);
}
} catch (err) {
console.log(`Error fetching and parsing data: `, err);
}
};
Don't think this is a Promise related issue at heart.
You'll need to collect your sites into an array that is initialized outside the loop. Then when getSubURLs() resolves, it will resolve to your array:
const getSubURLs = async() => {
let urls = await getURLS();
let siteList = [];
try {
for (const url of urls) {
// :
// :
// :
siteList.push(sites);
}
} catch (err) {
console.log(`Error fetching and parsing data: `, err);
}
return siteList; // array of objects
};
getSubURLs().then(console.log);

UI update with GET method

I'm working on a project to get the api from openweathermap using node js & express & then update the UI.
I'm trying to update the UI of the page with the GET data, but it does not work. it prints undefined instead of the required values.
it works and gets the api from openweathermap on the terminal & console.
any help would be appreciated!
/* Global Variables */
const date = document.getElementById('date').value;
const temp = document.getElementById('temp').value;
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();
//baseURL & apiKey
const baseURL = `http://api.openweathermap.org/data/2.5/weather?zip=`;
const apiKey = `&appid=...`;
//event listener when user clicks generate button
const button = document.getElementById('generate');
button.addEventListener('click', performAction);
//event listener function
function performAction(event) {
const zip = document.getElementById('zip').value;
const feelings = document.getElementById('feelings').value;
getData(baseURL, zip, apiKey)
.then(function (data) {
console.log(data);
postData('/add', {date: newDate, temp: data.main.temp, feelings: feelings});
updateUI();
})
};
//function to fetch api data
const getData = async (baseURL, zip, apiKey) => {
const res = await fetch(baseURL+zip+apiKey)
try {
const data = await res.json();
return data;
console.log(data);
}catch(error) {
console.log("error", error);
}
}
// user input post data function
const postData = async (url = '', data = {}) => {
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
});
try {
const newData = await response.json();
}catch (error) {
console.log("error", error);
}
};
//updating UI
const updateUI = async () => {
const request = await fetch('/all');
try{
const allData = await request.json();
document.getElementById('date').innerHTML = allData.date;
document.getElementById('temp').innerHTML = allData.temp;
document.getElementById('content').innerHTML = allData.content;
}catch(error){
console.log("error", error);
}
}

Categories

Resources