jnorris
jnorris

Reputation: 6510

How do you create a JSON object within a JSON array using Ruby's json_builder?

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

Upvotes: 1

Views: 1350

Answers (3)

Garrett
Garrett

Reputation: 8090

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.

Upvotes: 4

jnorris
jnorris

Reputation: 6510

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

require 'json'

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

puts JSON.pretty_generate(json)

Upvotes: 0

Swanand
Swanand

Reputation: 12426

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.

Upvotes: 2

Related Questions