【问题标题】:How to retrieve the json object specific values?如何检索 json 对象的特定值?
【发布时间】:2012-06-21 12:46:18
【问题描述】:

我有一个包含以下 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() 方法,但它说不能将数组转换为字符串。

我该怎么做,知道吗?

【问题讨论】:

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


    【解决方案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" 键。

    【讨论】:

    • 感谢您的想法并纠正我,但是当我尝试使用 JSON.parse() 方法解析 json 对象时,它会引发错误 - 无法将数组转换为字符串。我该如何克服这个错误?
    • 也许是一个json对象数组?将 parse 语句移动到循环中。
    • 你的意思是这样的 - @news_feed.each_with_index do |item, i| to_return += "#{i+1} #{JSON.parse(item["feed_detail"]["title"])}
      " end 当我尝试这个时,它给了我一个错误 - 未定义的方法`[] '。我还能做什么?
    猜你喜欢
    • 2021-09-02
    • 2019-05-10
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多