0

I've parsed a json file (which consists of a single array called "items" containing 4 key-value pairs) into an OpenStruct so that I can treat my data as if they were objects. I would now like to display each object at random on a web page.

# read json file and parse into OpenStruct
def read_json(url)
    json_file = File.read(url)
    json_obj = JSON.parse(json_file, object_class: OpenStruct)
    return json_obj
end

# sample array
def random_display(json)
    out = json.items.sample
    return out
end

My json is basically like:

{
    "items": [
        {
            "foo": "bar",
            "foo": "bar"
        },
        {
            "foo": "bar",
            "foo": "bar"
        },
}

And then finally in my Sinatra routes, I've got:

get '/' do
  @data = read_json("public/data.json")
  @random = random_display(@data)
  erb :index
end

In my erb page I'm using <%= @random %> and getting a simple # as the result. Why? I mean, I'm aware that it's because I'm not telling it to show the value of any one particular key. But how do I work around that?

Another thing - I feel like the way I'm going about what I'm trying to do (which is create a little game that asks you to pick the more expensive of two random options) - is fundamentally wrong.

tadman
  • 208,517
  • 23
  • 234
  • 262
calyxofheld
  • 1,538
  • 3
  • 24
  • 62
  • 1
    Try escaping it: `<%= h(@random) %>` – tadman Sep 12 '16 at 03:39
  • Did this and got "undefined method 'h'" – calyxofheld Sep 12 '16 at 03:44
  • 1
    Look at the raw source of your page HTML. You need to HTML escape that somehow, so whatever method does that job is the one you use here. I thought `h` was built-in to ERB but I must be wrong. – tadman Sep 12 '16 at 03:46
  • Hm, okay. So Inspector shows a random openstruct object each time I refresh the page, but the only thing showing in the browser window is the "#". h is the escaping character for Rails - in erb it's adding another `%` so that your variable looks like this: `<%%= @random %>`. That, however, removes the openstruct object from Inspector completely, and prints `<%= @random %> to the page instead of the #. – calyxofheld Sep 12 '16 at 03:56
  • 1
    Then you need to follow the [recommendations in this question](http://stackoverflow.com/questions/2123586/how-do-i-html-escape-text-data-in-a-sinatra-app). – tadman Sep 12 '16 at 04:17

0 Answers0