user1938700
user1938700

Reputation: 39

JSON will not display

I have a Sinatra application that should get image URLs from a JSON file and put them into HTML <img> tags.

I can parse through the JSON just fine when I print it to the command line, but when I use ERB to place the data, it won't show.

I put it in <ul> tags and got only the bullet points for every image in the JSON file.

Here is my code:

app.rb:

get "/" do

    file = open("./images.json")
    json = file.read

    @parsed = JSON.parse(json)

    erb :roar

    #@parsed.each do |roar|
    #  p roar["url"]
    #end

end

Roar.erb:

<ul>
 <% @parsed.each do |shop| %>
 <li> <%shop["url"] %> </li>

 <% end %>
</ul>

Upvotes: 0

Views: 128

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

Just some comments on the code in general:

Don't use:

file = open("./images.json")
json = file.read

@parsed = JSON.parse(json)

Instead, use:

json = File.open("./images.json") do |fi|
  fi.read
end

@parsed = JSON.parse(json)

Or:

json = File.open("./images.json") { |fi| fi.read }
@parsed = JSON.parse(json)

Or:

json = File.read("./images.json")
@parsed = JSON.parse(json)

Or:

@parsed = JSON.parse(File.read("./images.json"))

The reasons are:

  • file = open("./images.json") opens the file but never closes it. That's not good form, and it's also not idiomatic Ruby. The first two replacements automatically close the opened file.
  • Using File.read returns the contents of the file just as opening it and reading in a separate step, only it's all in one step. The file is also automatically closed afterwards.

Upvotes: 1

Martin
Martin

Reputation: 7714

Are you not just missing an "=" here :

<li> <%= shop["url"] %> </li>

Upvotes: 1

Related Questions