Javascript can't find data files

I’ve been trying to access my local json file from javascript but continue to receive a console error that the json file can’t be found. But that same data file is accessible from my erb templates, so I know the json file is properly structured and that my paths are correct.

My directory structure looks like this:

  • data
    • teams.json
  • source
    • javascript
      • wc.js

If I try to access the data in an erb template like the following, everything works:

<% data.teams.items.each do |i| %>
  <h1><%= i.title %></h1>
  [more HTML here]
<% end %>

If I try to access the data in a javascript function like the following, the console error says it can’t be found:

data.teams.items.forEach(function(team) {
  if (team.slug === teamSlug) {
    renderTeamData(team);
    return;
  }
});

I’ve spent a good deal of time researching this and trying to find a solution. I would be SO grateful if someone could help me figure this out.

Thanks in advance.

Edit: I thought it prudent to mention that I have tried different paths, none of which helped. I tried “/data/teams.json,” “data/teams.json,” and “/…/data/teams.json.”

Middleman is a Ruby library and therefore parses the files under /data to Ruby. These /data files can be written in YAML or JSON, but using JSON doesn’t magically make them available in JavaScript. You still have to hand over the Ruby variable to JS yourself.

So you need to call data.teams.items.to_json in Ruby to get a string, hand that string over to JS and then there call JSON.parse().

There are multiple ways to make the handover:

1 Like

Thanks, friend. That’s super helpful. I’m going to give this a go.