Lesson 4 โ€” Your Herd as Data

JSON ยท done when the table is built from a list, not typed by hand

Four animals in HTML is fine. Forty is a mess. JSON is how we write a herd as data: names, tags, weights โ€” a list the computer can loop over.

Live result

Same looking card. The rows are drawn by JavaScript from a list.

Step 1 โ€” the shape

One animal looks like this. Curly braces, keys, values, commas. Quotes around text. Numbers bare.

{
  "name": "Black Gold",
  "tag": "FW-01",
  "breed": "Texas Longhorn",
  "notes": "Rare black pattern, 100\"+ horns",
  "startWeight": 1100,
  "currentWeight": 1280
}

The whole herd is an array: square brackets, animals separated by commas.

Step 2 โ€” put the list in script.js

In this lesson the data still lives in JavaScript. Next lesson it moves to its own file.

var herd = [
  { "name": "Black Gold", "tag": "FW-01", "breed": "Texas Longhorn", "notes": "Rare black pattern", "startWeight": 1100, "currentWeight": 1280 },
  { "name": "Brutus", "tag": "FW-02", "breed": "Texas Longhorn", "notes": "Largest steer", "startWeight": 1400, "currentWeight": 1520 },
  { "name": "McCree", "tag": "FW-03", "breed": "Texas Longhorn", "notes": "Strong presence", "startWeight": 1200, "currentWeight": 1310 },
  { "name": "Blacksmith", "tag": "FW-04", "breed": "Texas Longhorn", "notes": "Newer addition", "startWeight": 1050, "currentWeight": 1180 }
];

var tbody = document.getElementById("herd-body");
herd.forEach(function (animal) {
  var gain = animal.currentWeight - animal.startWeight;
  tbody.insertAdjacentHTML("beforeend",
    "" + animal.name + "" + animal.tag + "" +
    animal.startWeight + "" + animal.currentWeight + "" +
    gain + " lbs"
  );
});

HTML tbody starts empty. JavaScript fills it. Add a fifth animal in the list and refresh โ€” the table grows. That's the point.

โ† Lesson 3 All lessons Lesson 5 โ€” fetch โ†’