how to create a custom json from raw data (database data)
I have create a show method in tour controller and want to render the data from the database into json format. This the definition of the tour controller
class ToursController < ApplicationController
respond_to :json
def show
@tourcategory = Tourcategory.find(params[:id])
@tours= @tourcategory.tours
@tourcategories = Tourcategory.all
render :layout => false
end
end
This is the definition of the show.html.haml view
%h3 Tour for #{@tourcategory.title}
= @tours.to_json
The output of this code is following:
[{"content":"dscfds","created_at":"2015-12-12T09:48:32Z","elementid":"test1","id":8,"jobid":2,"next_button_title":"next","priority":23,"title":"test1","updated_at":"2015-12-12T09:48:32Z"}]
But i just want to render the data in this kind of json format, following:
var tour = {
id: "tour",
steps: [
{
title: "abc",
content: "Click this Button.",
target: "#abc",
placement: "bottom",
showNextButton: false,
skipIfNoElement : true
},
It's not clear what you're trying to achieve but it seems to me that you want to extract certain attributes from your @tours
and group them as an array, if that's the case you can do something like this:
(list all the attributes you want inside t.attributes.slice()
)
tour = { id: "tour", steps: @tours.map { |t| t.attributes.slice("title", "content", "target") } }
and if you want to convert your keys from snake (underscore) to camel format:
tour = {
id: "tour",
steps: @tours.map {|t| t.attributes.slice("title", "content").map {|k,v| [k.camelize(:lower), v]}.to_h}
}
链接地址: http://www.djcxy.com/p/47168.html