将静态JSON文件解析为rails对象

时间:2015-11-21 15:37:56

标签: ruby-on-rails ruby json ruby-on-rails-4 flickr

我正在尝试将我的根目录中的静态JSON文件解析为已经预定义的对象,但我对如何让对象“读取”JSON文件中的每个属性并将其显示为拥有。我希望我不会因为它的内容而让它更加混乱?

我的一些代码:

   class PostsController < ApplicationController
  # before_action :set_post, except: [:index, :show]

  # @@posts = File.read('app/assets/javascripts/flickr_feed.json')
  # @posts = JSON.parse(string)

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
    respond_to do |format|
      format.html
      format.json { render json: @@posts }
      # format.json { render json: @@posts }
    end
  end

  # GET /post/1
  # GET /post/1.json
  def show
    @post = @post.assign_attributes JSON.parse(File.read('app/assets/javascripts/flickr_feed.json'))
    respond_to do |format|
      format.html
      format.json { render json: @post }
    end
  end
  ...

如果我转到localhost:3000/posts.json,我会看到欲望输出..

{
"title": "Recent Uploads tagged potato",
"link": "https://www.flickr.com/photos/tags/potato/",
"description": "",
"modified": "2015-11-21T08:41:44Z",
"generator": "https://www.flickr.com/",
"posts": [ // before was "items":
 {
  "title": "Hokkaido potato with butter",
  "link": "https://www.flickr.com/photos/taking5/22873428920/",
  "media": {"m":"https://farm6.staticflickr.com/5813/22873428920_3cac20cc47_m.jpg"},
  "date_taken": "2015-07-18T08:16:24-08:00",
  "description": " <p><a href=\"https://www.flickr.com/people/taking5/\">Taking5<\/a> posted a photo:<\/p> <p><a href=\"https://www.flickr.com/photos/taking5/22873428920/\" title=\"Hokkaido potato with butter\"><img src=\"https://farm6.staticflickr.com/5813/22873428920_3cac20cc47_m.jpg\" width=\"240\" height=\"180\" alt=\"Hokkaido potato with butter\" /><\/a><\/p> <p>Yummy.<\/p>",
  "published": "2015-11-21T08:41:44Z",
  "author": "nobody@flickr.com (Taking5)",
  "author_id": "58375502@N00",
  "tags": "japan hokkaido potato hakodate morningmarket"
 }
]
}
 ...

但如果我去posts#index我什么也看不见。我知道我没有正确解析数据,但我对如何做到这一点感到困惑。任何帮助将非常感谢。感谢

TL; DR:我想从JSON文件中解析每个,以便能够post.titlepost.description,等

编辑1:代码拼写错误更新。

编辑2:更新控制器中的代码

1 个答案:

答案 0 :(得分:3)

您可以尝试:

@post = Post.new
@post.assign_attributes JSON.parse(File.read('app/assets/javascripts/flickr_feed.json'))

如果您使用protected_attributes gem,则必须在模型中使用attr_accessible定义使用此方式设置的属性,或者必须使用参数without_protection

编辑:

def index
  @posts =
    JSON.parse(File.read('app/assets/javascripts/flickr_feed.json'))["posts"].inject([]) do |_posts, post_attrs|
      _posts << Post.new(post_attrs)
    end
  respond_to do |format|
    format.html
    format.json { render json: @posts }
  end
end