how to parse json from an url into html by using javascript (programmatically) and i facing an problem with this ?
api: https://corona.ps/API/summary
You need to use the built in JavaScript fetch() method which returns a promise. Use .then() to handle the response and .catch() to handle any errors relating to the fetch call.
Here's an example function using your api link:
function getData () {
fetch("https://corona.ps/API/summary")
.then(res => res.json())
.then(data => console.log(data)) // will log js object
.catch(err => console.log(err))
}
Related
in the following code
useEffect(() => {
fetch(options.url)
.then((response) => response.json()
.then((r) => setData(r)));
}, [options.url]);
what does response.json() do ? why do we need to do a .json(), would it be fine if one did not invoke that function?
response.json() reads the Response's body as a ReadableStream, parses it as JSON, and returns the parsed data in an asynchronous Promise.
Without doing this, you'd have the Response object, but you wouldn't be able to access the data inside it right away.
Sorry if this was posted a lot, I read through several articles but could not find the solution. So, I'm fetching a large JSON from this API, and I would like to cache the response somehow in the localStorage, so the next time the page loads, the scripts first checks if there is an object with the requested ID inside the JSON, and renders the content if there is one - and if there isn't, goes of to the API to fetch it.
I was thinking of setting up two fetch() functions, and this is what I have:
fetch(url + id)
.then((response) => {
localStorage.setItem('myResponse', response);
})
.catch((error) => {
console.log(error);
})
Then, check if there is something saved inside the localStorage, and if it is good, use it to render the HTML, if not, go on to another fetch to get it from the API.
if(localStorage) {
createHTML(localStorage.myResponse);
} else {
fetch(url + id)
.then(response => response.json())
.then(data => createHTML(data))
}
But, in the first fetch, if I use JSON.stringify(response), it just shows it as an empty object, so it the localStorage it looks like: myResponse - {}. If I do console.log(response.json()); on the first fetch, it shows PromiseĀ {<pending>}.
I've tried to make something out of that, but without results...any help much appreciated!
response.json() is a Promise, it needs to be either awaited, or chained a .then(); If you simply log it as is, all you'll get is Promise {<pending>} because it hasn't resolved yet.
fetch(url + id)
.then( response => response.json() )
.then( json => {
localStorage.setItem('myResponse', JSON.stringify(json));
})
Or with the async/await syntax :
const response = await fetch(url + id);
const json = await response.json();
localStorage.setItem('myResponse', JSON.stringify(json));
Take a simple API fetch call, such as follows:
fetch('https://api.nasa.gov/planetary/apod?api_key=xxxxxxxxx')
.then(res => res.json())
.then(data =>setPic(data.hdurl))
I'm still a bit confused about how this works. My understanding is this - information is sent from the web server as JSON, but to displayed on a web page it has to be converted into a normal JS object. Is this correct?
And if so, how does the above method convert JSON to a JS object? Because as I understand it, res.json simply extracts the JSON, it doesn't convert it.
[...] how does the above method convert JSON to a JS Object? Because
as I understand it, res.json() simply extracts the JSON, it doesn't
convert it.
This is what .json() does - it resolves the JSON string and parses it into a JS Object:
// Retrieves data from a URL
fetch('data:text/plain;charset=utf-8,%7B%22myJSON%22%3A%20%22myJSON%22%7D')
// Resolve the data retrieved from the URL as JSON and parse into a JS Object
.then(res => res.json())
// Work with the resolved data
.then(data => {
console.log('data has been resolved as: ' + typeof data);
console.log(data);
});
If you want the JSON String to remain a JSON String, you can use .text() instead:
// Retrieves data from a URL
fetch('data:text/plain;charset=utf-8,%7B%22myJSON%22%3A%20%22myJSON%22%7D')
// Resolve the data retrieved from the URL as a string
.then(res => res.text())
// Work with the resolved data
.then(data => {
console.log('data has been resolved as: ' + typeof data);
console.log(data);
});
I know how to fetch JSON with the Fetch API like this:
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
I tried to replicate the same thing to get MsgPack or YAML data, but all my attempts have failed. I obviously know how to deserialize data, but I suspect I feel a bit lost with chained promises which I don't fully grasp. Since there is no response.yaml(), I need to us an extra step but I can't make it work. I tried with response.body() and response.blob(). Each time I do it, no data is available at the time of the console log. Which I assume means that my data is still a promise instead of being processed and called with the callback.
I have tried things like:
fetch('http://example.com/movies.json')
.then(response => response.body())
.then(data => console.log(deserialize(data)));
or:
fetch('http://example.com/movies.json')
.then(response => response.body())
.then(raw => deserialize(raw))
.then(data => console.log(data));
Here deserialize is a placeholder for the deserialize/decode function for either format.
Anybody has an example using YAML (I suspect more popular than MsgPack).
Maybe this npm package can help you with parsing yaml data: https://www.npmjs.com/package/js-yaml, https://github.com/nodeca/js-yaml.
example.yaml:
docker:
- image: ubuntu:14.04
- image: mongo:2.6.8
command: [mongod, --smallfiles]
- image: postgres:9.4.1
This works for me:
fetch('/example.yaml')
.then(res => res.blob())
.then(blob => blob.text())
.then(yamlAsString => {
console.log('yaml res:', yamlAsString)
})
.catch(err => console.log('yaml err:', err))
First we convert the result to a Blob. After that we call the text() method on it which converts the blob to a string.
https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
I am trying to use the d3.json method to access JSON Data from an endpoint. I am able to successfully access the data using the fetch method below, however I am not sure how to change this to the d3.json method. How can I pass the argument "credentials:include"
fetch('http://0.0.0.0:example.com',{
credentials: 'include'
})
.then(response => response.json())
.then( json => console.log(json))
My attempt would be something like this, however I am not sure where I would add the credentials argument.
d3.json('http://0.0.0.0:example.com', json => console.log(json))
d3.json use fetch so the same will work
From the doc:
d3.json:
Fetches the JSON file at the specified input URL. If init is specified, it is passed along to the underlying call to fetch; see RequestInit for allowed fields.
d3.json('http://0.0.0.0:example.com', {credentials: "include"}, function(error, json) {
console.log(json);
})