如何在Rails控制器中格式化JSON? [英] How to format json in rails controller?
问题描述
如何在Rails控制器中格式化json?我通过link_to发送并获取方法params [:cat],然后我通过父对象(params [:cat])提取了所有子元素,但是如何为我的jqTree设置成json格式呢?因此,它看起来像{label:(这里是params [:cat]),孩子:[{all @ search_trees.id}]}}吗?
How to format json in rails controller? Via link_to i'm sending and get in method params[:cat], then i fetch all childrens via parent (params[:cat]), but how to format this all in json format for my jqTree? So it looks like {label : (here goes params[:cat]), children: [{all @search_trees.id}]} ?
require 'json'
@search_trees = SearchTree.find(:all, :include => [:designation], :conditions => { :STR_ID_PARENT => params[:cat]})
#data = "{ label : '10001', children : [{label : '10111'},{label : '10122'}] }"
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @search_trees }
format.json { render :json => data }
end
我将从这里的长问题中提取一部分问题:
I'll fetch a part of question from my long question here:
How to correctly do jquery tree in rails app?
她是我的json:
[{"search_tree":{"STR_DES_ID":42275,"STR_ID":10130,"STR_ID_PARENT":10726,"STR_LEVEL":4,"STR_NODE_NR":130,"STR_SORT":621,"STR_TYPE": 1,"designation_id":42275}},{"search_tree":{"STR_DES_ID":42277,"STR_ID":10132,"STR_ID_PARENT":10726,"STR_LEVEL":4,"STR_NODE_NR":132,"STR_SORT": 620,"STR_TYPE":1,"designation_id":42277}},{"search_tree":{"STR_DES_ID":43152,"STR_ID":10730,"STR_ID_PARENT":10726,"STR_LEVEL":4,"STR_NODE_NR": 730,"STR_SORT":622,"STR_TYPE":1,"designation_id":43152}},{"search_tree":{"STR_DES_ID":42209,"STR_ID":12344,"STR_ID_PARENT":10726,"STR_LEVEL": 4,"STR_NODE_NR":2344,"STR_SORT":623,"STR_TYPE":1,"designation_id":42209}}] 我需要这样输出 jqTree-从json创建树数据
[{"search_tree":{"STR_DES_ID":42275,"STR_ID":10130,"STR_ID_PARENT":10726,"STR_LEVEL":4,"STR_NODE_NR":130,"STR_SORT":621,"STR_TYPE":1,"designation_id":42275}},{"search_tree":{"STR_DES_ID":42277,"STR_ID":10132,"STR_ID_PARENT":10726,"STR_LEVEL":4,"STR_NODE_NR":132,"STR_SORT":620,"STR_TYPE":1,"designation_id":42277}},{"search_tree":{"STR_DES_ID":43152,"STR_ID":10730,"STR_ID_PARENT":10726,"STR_LEVEL":4,"STR_NODE_NR":730,"STR_SORT":622,"STR_TYPE":1,"designation_id":43152}},{"search_tree":{"STR_DES_ID":42209,"STR_ID":12344,"STR_ID_PARENT":10726,"STR_LEVEL":4,"STR_NODE_NR":2344,"STR_SORT":623,"STR_TYPE":1,"designation_id":42209}}] i need to output like this jqTree - creating tree data from json
推荐答案
如果要自定义json,可以使用RABL或JBuilder.您可以在此处找到截屏视频: http://railscasts.com/episodes/320-jbuilder?autoplay = true 并在此处: http://railscasts.com/episodes/322- rabl?autoplay = true .
If you want to customize your json, you can use RABL or JBuilder. You will find screencasts here : http://railscasts.com/episodes/320-jbuilder?autoplay=true and here : http://railscasts.com/episodes/322-rabl?autoplay=true.
这篇关于如何在Rails控制器中格式化JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!