1

How do I use Ruby's json_builder to create a JSON object within a JSON array? For example, how do I create the following structure?

{
  Object: [
    "x",
    { 
      "Foo" : "Bar" 
    },
    "y"
  ]
}

Note: these types of structures are used in AWS's Cloud Formation API

2
  • Perhaps the answer is "don't use json_builder" :( Commented Feb 7, 2012 at 5:34
  • Are there any similar ruby JSON templating DSLs that can do this cleanly? Commented Feb 7, 2012 at 5:39

3 Answers 3

4

Here is the example code needed to generate a JSON object as shown in the question.

require 'rubygems'
require 'json_builder'

json = JSONBuilder::Compiler.generate(:pretty => true) do
 Object ['x', { :Foo => 'Bar' }, 'y']
end

puts json

As the author of json_builder, let me know if you need any other help, but the README is fairly straightforward and could always use improvement if you have a hard time finding example usage.

Sign up to request clarification or add additional context in comments.

Comments

2

I would recommend JBuilder over json_builder. It is targeted at Rails applications, but its a Ruby gem and can be used otherwise.

The github page also has links to other json builder gems.

3 Comments

Any particular reason you recommend JBuilder over json_builder? As the author of json_builder, I spent a lot of time on the API of the library and would like to think it's the simplest JSON generating library out there without sacrificing features or speed.
Actually, I should have mentioned it here, I only recommended it because it was made a Rails default.
Also, the API being similar to the XML builder API is a minor, but added advantage of JBuilder.
0

Interestly, "regular" require 'json' works well as a DSL:

require 'json'

json = {
  :Object => [
    "x",
    {
      :Foo => "Bar"
    },
    "y"
  ]
}

puts JSON.pretty_generate(json)

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.