My rails app gets the following JSON feed from mixcloud and sticks the results into my index page
At the moment when I do this, the 开发者_StackOverflow社区entire contents of my feed are displayed unformatted in one big blob of scary looking text (without the curly JSON brackets)
I only want to display specific values from the feed in the view.
From the feed in question lets say for simplicity that I just wanted to display all values with a key of "url"
In case I'm doing something wrong here's my code:
# podcast controller
def index
# I'm using a class method to get the feed
@feed = Podcast.feed
end
# podcast model
def self.feed
feed = JSON.parse(open("http://api.mixcloud.com/alivefrommaryhill/feed").read)
end
# index.html.haml
.feed
= @feed
I can't figure out how to style the results and display only certain items from the feed. Is my approach wrong?
I've done something similar using HTTParty and Hashie gems.
This example loops through the first 10 results:
#controller
def index
@result = Hashie::Mash.new HTTParty.get("http://api.mixcloud.com/alivefrommaryhill/feed")
end
#index.html
<% @result.data[0..10].each do |e| %>
<%= e.url %>
<br/>
<% end %>
If you wanted the 'small pictures' you would do
<% @result.data[0..10].each do |e| %>
<%= e.from.pictures.small %>
<br/>
<% end %>
Hope this helps :-)
Instead of writing the json directly to your view, maybe you could write a clientside javascript function that converts the json into html markup. For, example, maybe use jquery like described here? Best way to display data via JSON using jQuery
Or, similarly, you could still write the json directly in your view, but write it out as the value to a javascript variable instead of writing it as html. Then you could write a javascript function that reads and parses the javascript variable after the page loads, converts it to html, and inserts into the DOM. This method would be similar to the answer in the link above, except you wouldn't have to make a ajax request, you can simply process the data since it will already be available locally in a js var.
精彩评论