Sangam Gupta
Sangam Gupta

Reputation: 1

How to retrieve the json object specific values?

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?

Upvotes: 0

Views: 2031

Answers (1)

DGM
DGM

Reputation: 26979

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.

Upvotes: 1

Related Questions