Reputation: 6510
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
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
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