0

I have an object containing information (news feed) in json format as follow:

def index
@news_feed = FeedDetail.find(:all)
@to_return = "<h3>The RSS Feed</h3>"
@news_feed.items.each_with_index do |item, i|
    to_return += "#{i+1}.#{item.title}<br/>"
    end

    render :text => @to_return
 end

I want to display only specific values from that json array, like title description etc. When I render directly @news_feed object it gives this

[{
    "feed_detail":{
        "author":null,
        "category":[],
        "comments":null,
        "converter":null,
        "description":"SUNY Levin Institute, Empire State Development Facilitate Collaboration to Drive Economic Opportunities Across New York State",
        "do_validate":false,
        "enclosure":null,
        "guid":null,
        "link":"http://www.suny.edu/sunynews/News.cfm?filname=2012-06-20-LevinConferenceRelease.htm",
        "parent":null,
        "pubDate":"2012-06-20T23:53:00+05:30",
        "source":null,
        "title":"SUNY Levin Institute, Empire State Development Facilitate Collaboration to Drive Economic Opportunities Across New York State"
    }
}]

When iterate over json object, it gives - undefined method items. All I want is to fetch only specific values from that array. I also used JSON.parse() method but it say cant convert array to string.

How would I do this, any idea?

0

1 Answer 1

1

You need to parse the json first:

@news_feed = JSON.parse(FeedDetail.find(:all))

Then you can access it like arrays and hashes:

@news_feed.each_with_index do |item, i|
  to_return += "#{i+1} #{item["feed_detail"]["title"]}<br/>"
end

In ruby, you access sub elements with [] not a . like javascript. Your sample json has no element named items so I removed that part. each_with_index will put each record into the item variable, and then you have to reference the "feed_detail" key before getting to the details.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the idea and correcting me, but I when I try to parse json object using JSON.parse() method it throws an error - can't convert Array into String. How do I over come this error?
perhaps it is an array of json object? Move the parse statement into the loop.
U mean something like this - @news_feed.each_with_index do |item, i| to_return += "#{i+1} #{JSON.parse(item["feed_detail"]["title"])}<br/>" end When I try this it gives me an error - undefined method `[]'. What else shall I do?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.