pandaman pandaman - 6 months ago 8
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

.html.erb
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.

Controller

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


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?

Answer

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

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

Also your file is not a valid JSON notation.

It should be:

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