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.

Was it helpful?

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}]}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top