简体   繁体   中英

What's the best way to parse JSON in Ruby on Rails?

I have the following json content that I'm pulling from a different location:

JSON

[
   {
      "global_event":{
         "ending_at":"2011-11-07T02:00:00Z",
         "short_url":"http://bit.ly/reAhRw",
         "created_at":"2011-10-04T14:25:41Z",
         "event_responses":[

         ],
         "addresses":{
            "location":{
               "city":"blah",
               "latitude":30.205288,
               "zipcode":"343434",
               "street":"blah",
               "longitude":-95.475289,
               "state":"TX"
            }
         },
         "body":"blahblahblah",
         "euid":"2f489d0c82d167f1c16aba5d3b4c29ade6f1d52a",
         "title":"Fusion",
         "updated_at":"2011-10-04T14:26:57Z",
         "event_roles":[

         ],
         "user":{
            "long_name":"Fusion Single",
            "nickname":""
         },
         "event_items":[

         ],
         "starting_at":"2011-11-07T00:00:00Z"
      }
   }
]

Controller

def events
    @json = ActiveSupport::JSON.decode(open('jsonfeed').read)
end

View

<ul>
<% @json.each do |event, data| %>
    <% event.each do |e, d| %>
        <li><%= e[:short_url] #doesn't work '%></li>
        <li><%= e['short_url'] #doesn't work '%></li>
    <% end %>
<% end %>
</ul>

Does anyone have any idea how I might be able to properly access the data within this json? Is there a better way to do it than the approach I'm taking?

To debug, just do something like this.

Your first loop is for an array, so only needs a single variable in the block:

<ul>
  <% @json.each do |event| %>
    <% event.each do |e, d| %>
      <li><%=h e.inspect %> / <%=h d.inspect %></li>
    <% end %>
  <% end %>
</ul>

It's hard to write something that will work exactly as we can only see the first event. But I'd be looking at the [ / { characters to see whether you're expecting a hash or an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM