Search code examples
ruby-on-railsrubyjsonruby-on-rails-2

How do I make a single element JSON array using the Rails XML Builder?


I am using a Rails app as an JSON API service. There is one field that can either hold one or two strings. Below is how I'm creating this JSON element in the .xml.builder file, getting the information from a flattened hash:

if hash['advertisements']
    hash['advertisements'].each do |ad|
        xml.advertisements(ad)
    end
end

When there are two strings in the hash, the resulting JSON is an array:

"advertisements": [
    "ad1.png",
    "ad2.png"
]

But when there is only one string, the element is simply a string:

"advertisements": "ad1.png"

Is there a way I can force the XML builder to make a JSON array, even if there is only one string in the hash? Also note that if there are no advertisements in the original hash, there should be no json array rendered.


Solution

  • Funny. I realized the app uses an XML builder template, convert it into a hash, then render it as json. (I did not develop this...) So I had to go in at the hash level using

    hash['advertisements'] = Array.hash['advertisements']
    

    That did the trick!