1

I am using JBuilder Ruby, and I want to create a JSON hash that looks like this, as an end result:

"must" : {
   "ids" : {
       "values" : [1,2]
   },
   "range" : {
       "visits" : 
         {
           "gte" : 10
         }

   }
}

Keep in mind I have no existing array to iterate over. All the examples I've looked at assume I have an array. I don't. I want to create this JSON on the fly.

2
  • What does your input data look like? Commented Jul 9, 2015 at 15:15
  • I have no input, that's what I mean when I say I have no existing array. I want to create this JSON on the fly. I have zero objects. Assume I have a blank slate to work with and I want to create a JSON response that looks exactly like the one I pasted above, with hard-coded values. Commented Jul 9, 2015 at 15:19

1 Answer 1

1

I don't recommend using Jbuilder for static data. The whole point of Jbuilder is to provide a DSL for converting complex object graphs into JSON. In this case, you might as well just convert a Ruby hash into JSON directly:

require 'json' # You'll need some type of JSON library which provides `Hash#to_json`
{
  must: {
    ids: {
      values: [1, 2]
    },
    range: {
      visits: {
        gte: 10
      }
    }
  }
}.to_json

For learning's sake, here's how you'd build the same JSON string with Jbuilder manually:

json = Jbuilder.new

json.set! :object do
  json.set! :must do
    json.set! :ids, [1, 2]
  end
  json.set! :range do
    json.set! :visits do
      json.set! :gte, 10
    end
  end
end.to_json # Note that Jbuilder even returns a Hash that need to be converted
Sign up to request clarification or add additional context in comments.

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.