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

Parsing a static JSON file into a Rails object

我正在尝试将静态 JSON 文件从我的根目录解析为一个已经预定义的对象,但我对如何让对象“读取”[ 中的每个属性感到困惑=36=] 文件并将其显示为自己的文件。我希望我没有把它弄得更混乱?

我的一些代码:

   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 我什么也看不到。我知道我没有正确解析数据,但我对如何解析感到困惑。

总结: 我想解析 JSON 文件中的每个 项目 以便能够 post.titlepost.description、等等

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

你可以试试:

@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