Question

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.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top