pandaman pandaman - 4 months ago 6
JSON Question

Rails controller is treating JSON object as a string

I have a static JSON file and want to iterate over it in an

template like,

<% @data.each do |x| %>
<%= x['method'] %>
<% end %>

But I'm running into an error like below.

undefined method `each' for #<String:0x007ffb11e33de8>

Rails seems to be interpreting the JSON as a string.


def index
@data ="#{Rails.root}/data/docs.json")


{method: "POST", usage: "xyz"},
{method: "DELETE", usage: "abc"},
{method: "GET", usage: "mno"}

This is confusing because in my text editor I can simply iterate over a json object like,

data.each {|x| p x}

Can anyone explain why this works differently in a Rails app?


First you should parse a Json file, because return a string object thats why an error is raised undefined method 'each' for #<String:0x007ffb11e33de8>:

def index
  @data = JSON.parse("#{Rails.root}/data/docs.json"))

Also your file is not a valid JSON notation.

It should be:

    { "method": "POST", "usage": "xyz"},
    {"method": "DELETE", "usage": "abc"},
    {"method": "GET", "usage": "mno"}