[Rails]一行代码完成自定义JSON格式数据
在Rails3中,增加JSON格式数据输出非常方便,只需在Controller中稍作修改即可。一种做法是在controller的开始处添加respond_to :json,然后使用respond_with响应请求。举例:假定有模型:书(book),有两个字段:书名(name)和作者名(author),controller为BooksController,将其index方法修改为(假定在index方法中输出JSON数据):
- class BooksController < ApplicationController
- // 支持html, xml ,json
- respond_to :html, :xml, :json
- def index
- @books = Books.all
- respond_with @books
- end
- // 其它方法忽略
- ...
- end
此时启动服务后(执行rails s),访问地址:http://localhost:3000/books/index.json将返回类似以下格式的数据:
- [
- "book":{"id":1,"title": "BookA","author":"Author1"},
- "book":{"id":2,"title": "BookB","author":"Author2"},
- "book":{"id":3,"title": "BookC","author":"Author3"}
- ]
某些情况下我们需要改变JSON输出格式,比如:需要把数以万计的记录缓存到客户端的localStorage或local database,去掉数据类型名称book以及字段名称id,name,author,将大大减小数据尺寸。如何改变这种格式输出呢?比如,输出为以下的数组格式:
- [
- ["1","BookA","Author1"],
- ["2","BookB","Author2"],
- ["3","BookC","Author3"]
- ]
一行代码足矣。编辑文件app/views/books/index.json.erb,填入以下内容:
- [<%= raw @books.map { |b| '["' + "#{b.id}" + '","' + "#{b.name}" + '","'"#{b.author}" + '"]' }.join(',') %>]
另一种有稍微改进的写法:
- [<%= raw @books.map { |b| %{["#{b.id}","#{b.name}","#{b.value}"]} }.join(',') %>]
(结束)
相关推荐
chenshuixian 2013-06-01
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20