0

Possibly an extremely newbie question here but anyway here goes.

I recently implemented a version of this javascript on my website to display blog post summaries.

I was wondering what changes would I need to make to have it load the same fields but get the data from a separate JSON file rather than having the JSON-like information in the same file?

I had a go myself but I couldn't quite work it out.

The only major difference I put in the code from that in the link was that I had "slice" instead of "Join" in the bit at the end.

Any help would be greatly appreciated as I'm horrendously new to Javascript.

  const petsData = [
  {
    name: "Purrsloud",
    species: "Cat",
    favFoods: ["wet food", "dry food", "<strong>any</strong> food"],
    birthYear: 2016,
    photo: "https://learnwebcode.github.io/json-example/images/cat-2.jpg"
  },
  {
    name: "Barksalot",
    species: "Dog",
    birthYear: 2008,
    photo: "https://learnwebcode.github.io/json-example/images/dog-1.jpg"
  },
  {
    name: "Meowsalot",
    species: "Cat",
    favFoods: ["tuna", "catnip", "celery"],
    birthYear: 2012,
    photo: "https://learnwebcode.github.io/json-example/images/cat-1.jpg"
  }
];

function age(birthYear) {
  let calculatedAge = new Date().getFullYear() - birthYear;
  if (calculatedAge == 1) {
    return "1 year old";
  } else if (calculatedAge == 0) {
    return "Baby";
  } else {
    return `${calculatedAge} years old`;
  }
}

function foods(foods) {
  return `
<h4>Favorite Foods</h4>
<ul class="foods-list">
${foods.map(food => `<li>${food}</li>`).join("")}
</ul>
`;
}

function petTemplate(pet) {
  return `
    <div class="animal">
    <img class="pet-photo" src="${pet.photo}">
    <h2 class="pet-name">${pet.name} <span class="species">(${pet.species})</span></h2>
    <p><strong>Age:</strong> ${age(pet.birthYear)}</p>
    ${pet.favFoods ? foods(pet.favFoods) : ""}
    </div>
  `;
}

document.getElementById("app").innerHTML = `
  <h1 class="app-title">Pets (${petsData.length} results)</h1>
  ${petsData.map(petTemplate).slice(0, 2)}
  <p class="footer">These ${petsData.length} pets were added recently. Check back soon for updates.</p>
`;
  • Does this answer your question? [read local JSON file into variable](https://stackoverflow.com/questions/48073151/read-local-json-file-into-variable) – Shane Creedon Apr 01 '20 at 20:02

2 Answers2

0

The fastest and easiest way is a work around, create a petsData.js file :

export default {

 petsData: [
  {
    name: "Purrsloud",
    species: "Cat",
    favFoods: ["wet food", "dry food", "<strong>any</strong> food"],
    birthYear: 2016,
    photo: "https://learnwebcode.github.io/json-example/images/cat-2.jpg"
  }
}

and import anywhere you need (update the filepath if necessary) like so:

import petsData from "./petsData.js";
console.log(petsData.petsData)
jcoleau
  • 1,112
  • 7
  • 20
0

You can fetch the data from the json via XMLHttpRequest

Here an example code:

let xhr = new XMLHttpRequest();
xhr.open("GET", "petsData.json");
xhr.addEventListener("readystatechange", function () {
 // any change in the request will result in calling this function
 // here you can check the readyState of the request (4 means DONE)
 // we want also the status to be 200 OK
 if (xhr.readyState === 4 && xhr.status === 200) {
  // here you are sure that the data has been fetched correctly
  let response = xhr.response;
  /* DO SOMETHING WITH response */
 }
});
xhr.send();