How to fetch JSON data into HTML?
JSON file is called data.json and has "day" and "amount" data that I want to put into
class="day-name" and class="daily-amount" elements.
19 Replies
you can import your javascript using
type="module"
:
And then import your JSON in javascript:
and then go from there
you'll have to loop over data
and update your HTML accordinglyI did that it is just that it is not working
I will send you my JS code
whoops
I did something like this
and few other versions
none worked
make a codepen, then I can take a look
I don't see anything immediately wrong with that atm
Sec
Let me figure out how to do it
Does it work?
Wait forgot the JSON
xD
But don't know how to do it
yeah, I didn't quite think about the json... what's the contents of the json file? can you paste it here?
Sure!
[
{
"day": "mon",
"amount": 50.45
},
{
"day": "tue",
"amount": 100.91
},
{
"day": "wed",
"amount": 52.36
},
{
"day": "thu",
"amount": 31.07
},
{
"day": "fri",
"amount": 23.39
},
{
"day": "sat",
"amount": 43.28
},
{
"day": "sun",
"amount": 25.48
}
]
I've set it up in a codesandbox, you can add more files in there. I see the logic flaw now, you're fetching
chartDailyAmount
once, and then assigning stuff to it, but you're assigning to the nodelist / array, not to a specific element in the arrayI did put them through
for loop
but it was still the same
I'm still confused. Usually it would work with chartDailyAmount[i].innerHTML
that wasn't in the code you shared though, and the [i] wouldn't be available in a for...of
I made another for loop inside of it
Kinda stupid, but I thought it would still work
Do you maybe have a proper for loop?
THat would work?
is there a reason you pre-fill the data in the HTML?
I was just practicing HTML/CSS and basic JS, did not plan on doing anything with JSON. However it really does not look like something hard to execute.
Maybe it is?
And instead of prefilling the html. you could do this
Nice! Thanks for the help!
Yeah saw people do it that way instead but was just wondering if it could be done even with pre-written HTML. Either way thanks for help as well!
I wouldn't necessarily recommend my solution btw, it's very dependent on the order the data appears in and the data having the same number of records as the pre-populated HTML, which isn't generally something you should rely on. It's just the closest to what you had that works, Mark's solution is more robust and easier to work with / reason about
@jochemm Now I have the problem of data showing when I inspect the elements in browser, but not showing in console when I request them with console.log on page load.
It is a graph where it will be shown depending on data, now its just an empty graph. xD Will have to try different methods tomorrow