Javascript questions

I have a single javascript file where I’m doing all of my javascript work. One of my variables references a JSON array, and I’d like for that variable to output the raw output from a .json data file (the data is 100 lines long and will grow over time).

Here are my files:

data/questions.json 

source/javascripts/javascript.js.erb

Code I’m trying to get to work within javascript.js.erb

var data = <% data.questions %>

where ideally it would just output the raw file exactly as it is from questions.json, but Middleman seems to want to parse it because it errors out with “NoMethodError: undefined method questions”.

Is there a way to do this?

Yes, you we’re pretty close actually: <%= data.questions.to_json %> should work. But if that file is 100 lines long and growing, it might be better to make an ajax request for it asynchronously.

Brilliant, that worked - thank you!

1 Like