【发布时间】:2015-11-21 15:37:55
【问题描述】:
我正在尝试将根目录中的静态 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 我什么也看不到。我知道我没有正确解析数据,但我对如何做到这一点感到困惑。
总结:我想解析JSON文件中的每个item,以便能够做到post.title、post.description等。
编辑:更新控制器中的代码。
【问题讨论】:
-
提示:当您执行
format.html时,它需要一段代码(大括号之间的一些代码,就像您对format.json的代码一样) -
@Sunil D,尝试了您推荐的
format.html{ render @posts },但现在它说我缺少部分内容,当我创建部分内容时,<%= render partial: @posts -%>得到了stack too deep error
标签: ruby-on-rails ruby json ruby-on-rails-4 flickr