1

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.

2 Answers 2

7

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}]}
Sign up to request clarification or add additional context in comments.

1 Comment

I was hoping to avoid converting the hash key & value into a two-element array, but so far this is the only way I've found that works.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.