Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

489
Visualizações
How do I fetch .json data into HTML using only JavaScript?

I am trying to display multiple arrays from a JSON file in an html document but I always get errors such as "undefined" or that it doesn't display all of the arrays.

Here's my json:

 "accounts": [
        {
            "website": "netflix.com",
            "username": "user@mail.com",
            "password": "aSecurePassword"
        }
    ]

and here's my .js and .html:

 <h2>JSON Data to HTML</h2>
    <div id ="data" class="accounts">
        <div class="website">website</div>
        <div class="user">user</div>
        <div class="password">pw</div>
    </div>


    <script type="text/javascript">
        var mainContainer = document.getElementById("data");
        var div = document.createElement("div");
        
        fetch("./data.json")
        .then(function(response){
            return response.json();
        })
        .then(function(data){
            div.classList.add('website');
            mainContainer.appendChild(div);
            div.innerHTML = "" + data.website
        })
        
    </script>

The above coded example is supposed to add another line to the class "accounts" like this:

<div class="website">website</div>
<div class="user">user</div>
<div class="password">pw</div>
<div class="website">netflix.com</div>

however, it shows "undefined" in html and I don't understand why?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

As your json file contains,

{
    "accounts": [{
        "website": "netflix.com",
        "username": "user@mail.com",
        "password": "aSecurePassword"
    }]
}

The code here in the last .then() should be

.then(function(data){
        div.classList.add('website');
        mainContainer.appendChild(div);
        div.innerHTML = "" + data.accounts[0].website
    })
about 4 years ago · Juan Pablo Isaza Relatório

0

The data object contains the property account which is an array with your websites objects, as @VLAZ said.

To display all your data, you should use a loop in the second then, like this :

.then(data => {
    data["accounts"].forEach(item => {
        // append the data to the html here
        // you can get the website using item.website
    }
})
about 4 years ago · Juan Pablo Isaza Relatório

0

First of all, ensure you have the correct json format. In your case, it should look like this:

{
  "accounts": [
    {
      "website": "netflix.com",
      "username": "user@mail.com",
      "password": "aSecurePassword"
    }
  ]
}

Then you can create a file with a .json extension and save the data there.

In you .js, fetch the data as follows assuming everything is under the same folder:

fetch("./json.json").then((response) =>
  response.json().then((data) => {
    let mainContainer = document.createElement("div");
    mainContainer.classList.add("website");
    mainContainer.innerHTML = "Website";
    let websiteDiv = document.createElement("div");
    websiteDiv.classList.add("website");
    websiteDiv.innerHTML = data.accounts[0].website;

    let userDiv = document.createElement("div");
    userDiv.classList.add("user");
    userDiv.innerHTML = data.accounts[0].username;

    let passwordDiv = document.createElement("div");
    passwordDiv.classList.add("password");
    passwordDiv.innerHTML = data.accounts[0].password;

    mainContainer.appendChild(userDiv);
    mainContainer.appendChild(passwordDiv);
    mainContainer.appendChild(websiteDiv);

    document.body.appendChild(mainContainer);
  })
);

Now, this should work in the case where you have only one record. If you have multiple records, consider using a loop so that you can iterate through your entire dataset.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda