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.