【问题标题】:Rails - Add index key for json parsed valueRails - 为 json 解析值添加索引键
【发布时间】:2014-05-24 07:43:44
【问题描述】:

我正在使用rails 4.0.2。对于我的mobile api,我需要向其发送JSON 值。在这里,我在发送 JSON 时遇到了一些问题。我想用index key自定义我的JSON

例如,当我请求我的cities 控制器的index 时,

http:localhost:3000/cities.json

我得到了这样的JSON 值,

[
   {"id":1,"name":"AAAA"}, 
   {"id":2,"name":"BBBB"}, 
   {"id":2,"name":"CCCC"}
]

但我想用一些named objectarray 包围。

{
    "cities" :
    [
       {"id":1,"name":"AAAA"}, 
       {"id":2,"name":"BBBB"}, 
       {"id":2,"name":"CCCC"}
    ]
}

现在我在我的控制器中尝试了,

def index
    @cities = City.all

    respond_to do |format|
      format.html
      format.json{ render :json => @cities.to_json(:methods => [:image_url]) }
      # :methods => [:image_url] this is related to paperclip gem
    end
end

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-4 indexing key


    【解决方案1】:

    先试试这个:-

    def index
        @cities = City.all
        cit ={'cities' => @cities}
        respond_to do |format|
          format.html
          format.json{ render :json => cit}
        end
    end
    

    然后尝试:-

    def index
        @cities = City.all
        cit ={'cities' => @cities}
        respond_to do |format|
          format.html
          format.json{ render :json => cit.to_json(:methods => [:image_url]) }
        end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 2021-11-06
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 2021-06-19
      相关资源
      最近更新 更多