Search code examples
arraysjsondatabasetemplateshugo

How to call specific data from json object in array from a value in a separate object in hugo


I have a data file in Hugo that I am trying to access data from. It looks something like this:

{
  "schedule": {
    "week1": [
      {
        "day": 0,
        "away": 1,
        "home": 2,
        "completed": false,
        "score": {
          "away": [
            0,
            0,
            0,
            0
          ],
          "home": [
            0,
            0,
            0,
            0
          ]
        },
        "time": "6:15"
      },
      etc.
    ]
  },
  "teams": [
    {
      "uid": 0,
      "name": "Buffalo",
      "conference": 0,
      "division": 0,
      "tla": "BUF",
      "offense": 10,
      "defense": 10,
      "wins": 0,
      "loses": 0,
      "ties": 0
    },
    etc.
  ]
}

I have a range loop that takes each game in week one, and I want it to take the ID of the home team and select that number in the teams array.

For example, in .Site.Data.rfl_data.schedule.week1 finding game one and taking the .home value, and plugging it in to the teams array. In js it would look like data.teams[data.schedule.week1[1].home].name so if the home value was 0, it would out put the name of the 0th team in the teams array. I am trying to put this in hugo. I can access some data.


Solution

  • You can take a look at https://gohugo.io/functions/index-function/ .

    Here is a code sample you can use:

    <ul>
    {{ range .Site.Data.test.schedule.week1 }}
      <li>
        home: {{ .home }},
        team name: {{ index $.Site.Data.test.teams (.home | int) "name" }}
      </li>
    {{ end }}
    </ul>
    

    side note: .home is seen as float64, so you need to convert it into int.