Question

Given the following Ruby data structure:

data = { :a => 1, :b => 2 }

... I want to create the following JSON:

{"result":[
  {"letter":"a","number":"1"},
  {"letter":"b","number":"2"}
]}

How do I accomplish this using Rails' JBuilder?

Ideally, I'd like to go directly from the Hash to the JBuilder object, without translating the Hash to an Array first.

Était-ce utile?

La solution

It's easy.

require 'jbuilder'

data = { :a => 1, :b => 2 }

out = Jbuilder.encode do |json|
    json.result data do |kv|
        json.letter kv[0]
        json.number kv[1]
    end
end

puts out  #=> {"result":[{"letter":"a","number":1},{"letter":"b","number":2}]}

Autres conseils

I prefer this notation since it isolates the key from the value:

require 'jbuilder'

data = { :a => 1, :b => 2 }

Jbuilder.encode do |json|
    json.result data do |k, v|
        json.letter k
        json.number v
    end
end

Basically identical to the previous answer but a little simpler

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top