简体   繁体   中英

Using JBuilder (Ruby), how to create an array of hashes

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM