如何检索json对象的特定值?

时间:2012-06-21 12:46:19

标签: ruby-on-rails ruby ruby-on-rails-3

我有一个包含json格式信息(新闻源)的对象,如下所示:

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

我想只显示那个json数组中的特定值,比如标题描述等。当我直接渲染@news_feed对象时,它会给出这个

[{
    "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"
    }
}]

当迭代json对象时,它给出了 - 未定义的方法项。 我想要的只是从该数组中获取特定值。我也使用了JSON.parse()方法,但它说cant将数组转换为字符串。

我怎么会这样做,任何想法?

1 个答案:

答案 0 :(得分:1)

你需要先解析json:

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

然后你可以像数组和哈希一样访问它:

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

在ruby中,您可以使用[]而非.类似的javascript访问子元素。您的示例json没有名为items的元素,因此我删除了该部分。 each_with_index会将每条记录放入item变量中,然后您必须在获取详细信息之前引用"feed_detail"密钥。

相关问题