-5

I'm trying to fetch an API with Javascript, and it's working, but I can't figure out how to make readable. This is my code:

JS code

And this is the output:

How it looks like

I've done this with ES6 several times, but I don't understand how to do it in vanilla. Newbie question I guess, but would appreciate some help. Thanks in advance!

I tried to add JSON.stringify(data, null, 2); but it didn't help. I also tried to just fetch some of the endpoints by adding the name of the endpoint after data, but then nothing shows.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Cecilia R
  • 3
  • 2
  • Can you add [minimum reproducible code](https://stackoverflow.com/help/minimal-reproducible-example) and the response object? Also, the line `I've done this with ES6 several times, but I don't understand how to do it in vanilla ` can you elaborate this? – NeERAJ TK Jun 11 '23 at 10:09
  • well, that's stringified JSON alright - your result is exactly as you coded it – Jaromanda X Jun 11 '23 at 10:09
  • 2
    Uhh...ES6 is vanilla javascript... – Liftoff Jun 11 '23 at 10:10
  • 1
    1) Please include the code and the image in the post body itself. 2) ES6 by itself is vanilla JS and not even new thosedays. 3) The output looks fine. It's not formatted but ES6 doesn't format JSON either. You can look for a library that does that. – Noam Jun 11 '23 at 10:11
  • `JSON.stringify(data, null, 2);` is what you're looking for in terms of a built-in pretty printer, but you have to set the container to have `white-space: pre` since the output of stringify includes `\n` instead of `
    `.
    – Liftoff Jun 11 '23 at 10:14
  • Hi, I might have been a bit unclear, I have worked in React when I have fetched APIs is what I meant, I thought ES6 what related only to React :). I have now marked the correct answer below, It works now! I'm a newbie like I said, and I will try to also learn how to write better SO-questions in the future. Thanks for feedback! – Cecilia R Jun 12 '23 at 10:20

2 Answers2

-1
function fetchData() {
  fetch(URL)
    .then(response => response.json())
    .then(data => {
      const dataContainer = document.getElementById('dataContainer');
      // Extracting and displaying specific data
      data.forEach(item => {
        const headline = item.headline;
        const paragraph = item.paragraph;
        const itemElement = document.createElement('div');
        itemElement.innerHTML = `<h2>${headline}</h2><p>${paragraph}</p>`;
        dataContainer.appendChild(itemElement);
      });
    })
    .catch(error => {
      console.error('Error:', error);
    });
}

fetchData();

The API response data is assumed to be an array of objects. The data.forEach() method is used to iterate over each object in the array. Within the loop, the headline and paragraph properties are extracted from each object.

A new div element is created for each item, and its content is set using template literals to include the extracted data. This creates a structured HTML markup with the headline as an h2 element and the paragraph as a p element.

Finally, the newly created div element is appended to the dataContainer element on your webpage, which will display each item separately.

Ashar Khan
  • 16
  • 2
-1

You need to parse and extract the bits.

For example like this

const data = [{"vignette":"","order":"1","imageUrl":"","headlinePrefix":"JUST NU: ","headline":"Polisanmäler — timmar innan match","paragraphPrefix":"","paragraph":"AIK agerar efter nya avgångskrave t"},{"vignette":"#v-826f4b23-1df4-42c4-b20f-75 1aaa520117","order":"2","imageUrl":"https://static.cdn-expressen.se/images/8f/d7/8fd7fe0e7cf3 4cd9aaef1d47c34369e1/16x6/1280.png","head linePrefix":"","headline":"Elias sköts ihjäl i Farsta: \"Han var bara ett barn\"","paragraphPrefix":"","paragraph":"15-åringens familj fick tvätta bort hans blod. \"Bråkade inte med någon\""}, {"vignette":"","order":"3","imageUrl":"https://stati c.cdn-expressen.se/images/54/b6/54b6560a8d ef4b889b4d6ab12652be80/16x6/1280@40.jp g","headlinePrefix":"","headline":"Fattar ingenting efter fruns sms - mitt i tv-sändningen","para graphPrefix":"","paragraph":"Alexander Axén om orden som skapade panik: \"Skrev att hon slåss\""}]


document.getElementById('dataContainer').innerHTML = data
  .map(item => `<h2><b>${item.headlinePrefix || ""}</b> ${item.headline}</h2>
<p>${item.paragraph}</p>`).join('<hr/>')
<div id="dataContainer"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236