I try to set data to my highchart with a fetch function but the dta is not displayed or even set to my chart element.
Here is my fetch function
fetch("data.csv")
.then(response => response.text())
.then((response) => {
//console.log("d"+response)
function csvToArray(str, delimiter = ",") {
let array = str.split("\n").map(function (line) {
return line.split(delimiter);
});
return array;
}
let array = csvToArray(response);
array.splice(0, 1);
array.splice((array.length-1),1)
let string =JSON.stringify(array);
let stringnew = string.replaceAll("\"","");
//console.log(csvToArray(response));
//console.log(csvToArray(response)[0]);
console.log(stringnew);
chart.series[0].setData(stringnew);
})
.catch(err => console.log(err))
as well as my data.csv file
time,data
1672683118394,12.00
1672683159084,10.00
1672683199305,9.00
I also see in the console the right output
[[1672683118394,12.00],[1672683159084,10.00],[1672683199305,9.00]]
its corrosponding to the Highcharts doku as I understood. But the data is not loaded.
Any help appreciated :)
stringnew is a string not a JSON object.
The issue is solved by using
JSON.parse(stringnew)
Related
I am trying to fetch the weather forecast api json like I did with the current weather api, but it does not seem to work any way I try.
let inOneDay = {
fetchWeather: function(){
fetch("https://api.openweathermap.org/data/2.5/forecast?q=Dortmund&units=metric&cnt=1&appid=758fce6dd3722cf25cd213a13bbc5484"
).then(resp => resp.json())
.then(data => console.log(data));
}
};
I have no idea where I went wrong. I used the same logic to make the code below work:
let weather = {
fetchWeather: function(){
fetch("https://api.openweathermap.org/data/2.5/weather?q=Dortmund&units=metric&appid=758fce6dd3722cf25cd213a13bbc5484"
).then((response) => response.json())
.then((data) => this.displayWeather(data));
},
displayWeather: function(data){
const{icon,description} = data.weather[0];
const{temp} = data.main;
document.querySelector(".icon").src = "https://www.openweathermap.org/img/wn/" + icon + ".png";
document.querySelector(".celsius").innerText = Math.round(temp) + "°C";
document.querySelector(".desc").innerText = description;
}
}
Grateful for any ideas!
Examining the json reply from that API, it looks like the OP code expects different fields than the service provides.
const result =
{"cod":"200","message":0,"cnt":1,"list":[{"dt":1631577600,"main":{"temp":13.31,"feels_like":13.05,"temp_min":13.31,"temp_max":15.87,"pressure":1018,"sea_level":1018,"grnd_level":1007,"humidity":90,"temp_kf":-2.56},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":95},"wind":{"speed":1.42,"deg":94,"gust":2.29},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2021-09-14 00:00:00"}],"city":{"id":2935517,"name":"Dortmund","coord":{"lat":51.5167,"lon":7.45},"country":"DE","population":588462,"timezone":7200,"sunrise":1631595820,"sunset":1631641686}};
const result0 = result.list[0]; // notice .list[0]
const weather0 = result0.weather[0]; // notice weather[0]
const main = result0.main; // notice main is a sibling prop to weather
const temp = main.temp
console.log(`weather is ${JSON.stringify(weather0)}`);
console.log(`main is ${JSON.stringify(main)}`);
console.log(`temp is ${temp}`);
Be sure to check for errors before dereferencing the result. It also looks like the api provides a cnt prop which might indicate the number of elements in the list.
I am trying to read a txt file line by line using fetch()
here is what I have:
fetch('http://localhost:8888/foo.txt')
.then(response => response.text())
.then((data) => {
var player = GetPlayer();
player.SetVar("phrase",data);
})
this code is reading the entire txt file at once and showing it on the "phrase" variable correctly.
But I want something like:
read line 1 -> show line 1 on the variable
read line 2 -> show line 2 on the variable
read line 3 -> show line 3 on the variable
...
Is that possible?
Thanks!
You can just use some String methods. You can use a .split() method with \n as the regex which will split your data into an array.
Example:
Let's suppose a text file at localhost:6060/foo.txt have the following content:
Format - username:password
Peter:NoLol1231#
Maffe:xDOkLmao
Loe:OOPSOkay
John:OhXDAlright
We can access the data in a proper way like this,
const fetch = require('node-fetch');
async function getData() {
return new Promise(resolve => {
let result = (await (await fetch("http://localhost:6060/foo.txt")).text()).split('\n');
let finalres = result.map((x) => ({[x.split(':')[0]]: x.split(':')[1]}));
resolve(finalres)
});
}
getData((d) => {
console.log(d["Peter"]); // Will print his password now!
});
I am learning how to use fetch APIs and I can't seem to figure out why only 1 image is showing up when using the Unsplash API. I think it has something to do with map, but I'm not sure. Any help our guidance is appreciated.
document.getElementById("search").addEventListener("click", () => {
const searchTerm = document.getElementById("searchBox").value;
console.log(searchTerm);
fetch(
`https://api.unsplash.com/search/photos?client_id=e72d3972ba3ff93da57a4c0be4f0b7323346c136b73794e2a01226216076655b&query=${searchTerm}`
)
.then(response => response.json())
.then(data => {
console.log(data);
console.log(data.results);
let searchResults = data.results
.map(searchResults => {
return (document.getElementById("app").innerHTML = `<img src="${
searchResults.urls.small
}">`);
})
.join("");
});
});
Code Sandbox here: https://codesandbox.io/s/yq918mok29
The default 10 images should appear but only 1 shows up. How can I map through the images and show them on the page?
You're overwriting the element's content in each map iteration, so you only see the last one. Use map to build the markup, then drop it into the document.
Something like this:
.then(data => {
let imagesMarkup = '';
data.results
.map(searchResults => {
return (imagesMarkup += `<img src="${searchResults.urls.small}">`);
}); // note that the join was removed here
document.getElementById("app").innerHTML = imagesMarkup;
});
Demo
I've used the 'fast-csv' module to parse the csv file for other manipulations, but that returns data row-wise. I want to read the first 2 columns of a csv file. Can someone please help?
I see two options.
One is do specify which headers you want in fast-csv and discard the rest. This approach will return an object which may suit your needs or you can then turn that into an array afterwards.
const csv = require('fast-csv')
const CSV_STRING = 'a,b,c\n' +
'a1,b1,c1\n' +
'a2,b2,c2\n'
let filtered = []
csv
.fromString(CSV_STRING, { headers: ['column_1', 'column_2'], renameHeaders: true, discardUnmappedColumns: true }) // I give arbitrary names to the first two columns - use whatever make sense
// .fromString(CSV_STRING, { headers: ['column_1', undefined, 'column_3'], discardUnmappedColumns: true }) // I could use undefined if I wanted to say skip column 2 and just want 1 and 3
.on('data', function (data) {
// console.log([data.column_1, data.column_2])
filtered.push([data.column_1, data.column_2]) // or you can push to an array
})
.on('end', function () {
console.log('done')
console.log(filtered)
})
The other is to return as an array (default) and filter what you need using the transform method
const csv = require('fast-csv')
const CSV_STRING = 'a,b,c\n' +
'a1,b1,c1\n' +
'a2,b2,c2\n'
csv
.fromString(CSV_STRING)
.transform(function (data) {
return [data[0], data[1]]
})
.on('data', function (data) {
console.log(data)
})
.on('end', function () {
console.log('done')
})
So I'm trying to use vanilla JavaScript and do a fetch from iTunes' API to create a page that allows a user to type in an artist name and then compile a page with like 15 top results. I'm using the following for my fetch:
function dataPull() {
fetch("https://itunes.apple.com/search?term=")
.then(function(response) {
if (response.status !== 200) {
console.log(response.status);
return;
}
response.json().then(function(data){
console.log(data);
let returnResponse = document.createElement("div");
let input2 = inputElement.value;
for (let i=0; i<data.length; i++){
if (inputElement===data[i].artistName){
console.log(data[i].artistName);
returnResponse.innerHTML = `
<div class="box">
<img src=${artWorkUrl30} alt="Album Image">
<p><span>Artist Name:</span>${data[i].artistName}</p>
<p><span>Track: </span>${data[i].trackName}</p>
<p><span>Album Name: </span>${data[i].collectionName}</p>
<p><span>Album Price: </span>${data[i].collectionPrice</p>
</div>
`;
results.appendChild(returnResponse);
}}
console.log(data);
});
}
)
The function is being called in a click event and I'm sure I can put everything from "let returnResponse" down to the append in another function. The issue I'm having is actually getting the API to show ANY results. At the moment if I type in Bruno Mars, Beethoven, or U2 it's not logging any data and it's giving me "Provisional Headers are Shown" when I check out the the Status Code.
Any thoughts on what I could do to make this better/work?
For full code:
jsfiddle
Typical fetch call will look like this.
fetch(`${url}`)
.then(response => response.json())
.then(json =>
// do something with the json
)
Modify your code and see if you can console.log() anything of note.
I would reccomend seperating your concerns. Making the dataPull function just get the results. That means you can use this code at other places without changing it.
Here the function returns the json object as a promise.
function dataPull(search) {
return fetch("https://itunes.apple.com/search?term="+search).then(res => res.json());
}
No you can call the dataPull function and resolve the promise. You'll have the result and can do what you want with it.
dataPull("test").then(res => {
console.log(res.results);
/*
res.results.forEach(item => {
div and span magic here
})
*/
})
Here's a link to a working JSFiddle.
https://jsfiddle.net/14w36u4n/