render out API data in custom format - javascript

I'm pulling data from an API which i then push it into a variable. From my script below the console reads like this
`1001,1002`
But i want it to render out in this format
(1001),(1002)
JS
this.http.post("http://localhost/app/route_list.php", { 'username': this.username}).map(res => res.json()) .subscribe(data => {
console.log(JSON.stringify(data));
var returned=[];
for(var i=0;i<data.length;i++){
returned.push(data[i].Route_ID);
console.log('this is data returned:'+returned)

Maybe this can help you:
this.http.post('http://localhost/app/route_list.php', {
username: this.username
})
.map(res => res.json())
.subscribe(data => {
const result = data
.map(item => `(${item.Route_ID})`)
.join(',');
console.log(result);
return result;
})

Related

How to treat JSON data in React?

I am using the following code using a flight data API:
useEffect(() => {
fetch(url, options)
.then((res) => res.json())
.then((json) => {
console.log(json);
datos.push(json)
})
.catch((err) => console.log('error' + err));
}, []);
return (
<div className='ejemplo'>
{JSON.stringify(datos)}
<div\>
)
and this is the result in the DOM:
[{"success":true,"data":{"2023-02-08":{"origin":"MAD","destination":"BCN","price":88,"airline":"UX","flight_number":7701,"departure_at":"2023-02-08T07:30:00+01:00","return_at":"2023-02-12T11:50:00+01:00","transfers":0,"expires_at":"2023-02-07T08:27:20Z"},"2023-02-09":{"origin":"MAD","destination":"BCN","price":69,"airline":"IB","flight_number":3034,"departure_at":"2023-02-09T21:15:00+01:00","return_at":"2023-02-13T18:05:00+01:00","transfers":0,"expires_at":"2023-02-07T08:27:20Z"},"2023-02-14":{"origin":"MAD","destination":"BCN","price":69,"airline":"IB","flight_number":3012,"departure_at":"2023-02-14T11:30:00+01:00","return_at":"2023-02-18T21:05:00+01:00","transfers":0,"expires_at":"2023-02-07T08:27:20Z"},"2023-02-15":{"origin":"MAD","destination":"BCN","price":69,"airline":"IB","flight_number":3034,"departure_at":"2023-02-15T21:15:00+01:00","return_at":"2023-02-19T14:30:00+01:00","transfers":0,"expires_at":"2023-02-07T08:27:20Z"},"2023-02-16":{"origin":"MAD","destination":"BCN","price":87,"airline":"IB","flight_number":3018,"departure_at":"2023-02-16T16:00:00+01:00","return_at":"2023-02-20T12:35:00+01:00","transfers":0,"expires_at":"2023-02-07T08:27:20Z"},"2023-02-17":{"origin":"MAD","destination":"BCN","price":57,"airline":"IB","flight_number":5003,"departure_at":"2023-02-17T22:20:00+01:00","return_at":"2023-02-21T20:30:00+01:00","transfers":0,"expires_at":"2023-02-07T08:27:20Z"},"2023-02-19":{"origin":"MAD","destination":"BCN","price":63,"airline":"UX","flight_number":7701,"departure_at":"2023-02-19T07:30:00+01:00","return_at":"2023-02-23T20:30:00+01:00","transfers":0,"expires_at":"2023-02-07T08:27:20Z"},"2023-02-21":{"origin":"MAD","destination":"BCN","price":69,"airline":"IB","flight_number":3012,"departure_at":"2023-02-21T11:30:00+01:00","return_at":"2023-02-25T14:30:00+01:00","transfers":0,"expires_at":"2023-02-07T08:27:20Z"},"2023-02-23":{"origin":"MAD","destination":"BCN","price":52,"airline":"UX","flight_number":7701,"departure_at":"2023-02-23T07:30:00+01:00","return_at":"2023-02-27T11:50:00+01:00","transfers":0,"expires_at":"2023-02-07T08:27:20Z"}
How can I modify my code in order to obtain just the origin, destination and price attributes? Thanks you all.
I tried to add a . plus the search attributes but no correct response was given.
You can loop your data by key and create a custom array of objects:
const [datos, setDatos] = useState([]);
useEffect(() => {
fetch(url, options)
.then((res) => res.json())
.then((json) => {
const { success, data } = json;
if (!success) console.log(error);
else {
const dataList = [];
for (const key in data) {
const { origin, destination, price } = data[key];
dataList.push({ origin, destination, price });
}
setDatos(dataList);
}
})
.catch((err) => console.log('error' + err));
}, []);
return (
<div className='ejemplo'>
{
datos.length > 0 && datos.map((d, index) => {
return <div key={index}>
<p>{d.origin}</p>
<p>{d.destination}</p>
<p>{d.price}</p>
</div>
}
}
</div>
)
You can extract only the desired attributes by using object destructuring in the .then function. Here's an example:
.then((json) => {
const {data} = json;
const flightData = Object.values(data).map(({origin, destination, price}) => ({origin, destination, price}));
datos.push(flightData);
})
In this example, Object.values(data) is used to get an array of flight data objects from the data object. Then, .map is used to extract only the origin, destination, and price properties from each object and create a new array of flight data objects with just those properties. This new array is then pushed to the datos array.

How to display data to Trading view chart using Alpha Vantage API?

fetch('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo')
.then(res => res.json())
.then(data => {
const cdata = data.map(d => {
{time:d[0],open:[1],high[2],low[3],close[4]}
});
candleSeries.setData(cdata);
})
.catch(err => log(err))
This My API DATA
When I run this code, there have an error like data.map is not function
Maybe you should Add Return before {time:d[0],open:[1],high[2],low[3],close[4]}
It's Like this
return {time:d[0],open:[1],high[2],low[3],close[4]}

How to fetch data from api?

I want to fetch data (particularly market cap)from api and display it inside my div. But my html diplays no data on execution. What could I be doing wrong?
<text id="result"></text>
<script>
// API for get requests
let fetchRes = fetch(
"https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX");
// fetchRes is the promise to resolve
// it by using.then() method
fetchRes.then((res) => res.json())
.then((result) => {
console.log(result);
document.getElementById('result').innerHTML = result.config.data.0.market_cap;
})
.catch(error => {
console.log(error);
})
</script>
Two suggestions:
Why not just chain the .then() directly to the fetch()?
You seem to have a bit of confusion on how to access the data in your structure - what you're after is result.data[0].market_cap.
// API for get requests
let fetchRes = fetch("https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX")
.then((res) => res.json())
.then((result) => {
console.log(result);
document.getElementById('result').innerHTML = result.data[0].market_cap;
})
.catch(error => {
console.log(error);
})
<text id="result"></text>
Aside: you should probably invalidate your API key that you've included here, as it's now out in public and can be used to forge requests as you to this API.
I am using jQuery Framework to do this easily.
Check the code below.
<script>
$.get(
"https://api.lunarcrush.com/v2",
{
data: "assets",
key: "n8dyddsipg5611qg6bst9",
symbol: "AVAX"
},
function (result){
data = JSON.parse(result);
}
);
</script>
You can use jQuery by adding the following code in your <head> tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Use result.config.data[0].market_cap; instead of result.config.data.0.market_cap;
let fetchRes = fetch(
"https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX");
// fetchRes is the promise to resolve
// it by using.then() method
fetchRes.then((res) => res.json())
.then((result) => {
console.log(result);
document.getElementById('result').innerHTML = result.config.data[0].market_cap;
})
.catch(error => {
console.log(error);
});
You can make it cleaner and simpler:
const fetchData = async(url) => (await fetch(url)).json();
fetchData("https://api.lunarcrush.com/v2?data=assets&key=n8dyddsipg5611qg6bst9&symbol=AVAX")
.then(res => {
result.innerText = res.data[0].market_cap;
})
.catch(err => {
console.log(err);
});
<text id="result"></text>

problem when try to fetch data from json file

I have some problems when I try to fetch the data, I didn't get response.
I write the path correctly?
I attached the part of the code and pic of my project hierarchy.
let transportation = [];
const init = () => {
fetch('/data/transportationDataCheck.json')
.then((response) => {
return response.json();
})
.then((data) => {
transportation = data;
}).then(() => {
renderList(transportation);
});
};
try this:
const data = require("../data/transportationDataCheck.json")
console.log(JSON.stringify(data));
Or you may try after changing little URL
let transportation = [];
const init = () => {
fetch('../data/transportationDataCheck.json')
.then((response) => {
return response.json();
})
.then((data) => {
transportation = data;
}).then(() => {
renderList(transportation);
});
};
You are trying to serve a static file with a fetch command, which inherently requires the file to be served by a server.
Someone had a similar issue here: Fetch request to local file not working
Depending on what type of file this is, you may not need to make a fetch. You could probably instead require the file:
var transportationDataCheck = require('./data/transportationDataCheck.json');```
Use ./ at the beginning of the path
fetch('./data/transportationDataCheck.json')
.then(response => {
return response.json()
})
.then(data => {
// Work with JSON data here
console.log(data)
})
.catch(err => {
// Do something for an error here
})

Using variables in multiple functions - react native

I'm looking to fetch some data then use it to fetch some other data, the first api returns a some news articles, I'm doing a for loop to access descriptions and save it as an array, I want then to use that array to make another fetch request, the issue is that I'm only able to access arrayin the first function, my code looks like that:
makeRemoteRequest = () => {
const url = `https://url.com`;
fetch(url)
.then(res => res.json())
.then(res => {
maindata = res.articles
var array = []
for(let i in maindata){
array.push(maindata[i].description)
}
console.log(array) // Working
this.setState({
data: res.articles,
});
})
console.log(array) // Not working
console.log(this.state.data) // Not working
};
I'm able to use this.state.data in component and render it on a listview.
Second function:
fetch('url', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'api_key': "81a354b",
'data': array
}),
})
My last attempt was to mix everything in a single function since it's all promises, didn't work
fetch(url)
.then(res => res.json())
.then(res => return res.articles.map(article => article.description) )
.then(res => fetch(otherUrl, { descriptions: res }))
.then(res => {
})
Just define the variable outside of the fetch scope first.
let array = [];
Then inside the fetch:
array.push()
What is the output of this? (could you please add the output formatted in your question?):
fetch(url)
.then(res => res.json())
.then(res => return res.articles.map(article => article.description) )
.then(res => fetch(otherUrl, { descriptions: res }))
//I assume that result needs to be parsed as json as well
.then(res => res.json())
.then(result => {
conole.log("got results:",results);
})
.catch(err =>
console.warn("something went wrong:",err);
)

Categories