开发者

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.ad开发者_JS百科vertisements(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.


I think the best and more simpler way is to use a JSON builder !

gem install json

the second idea is to use your ORM serializer. This way you won't have to handle all use cases.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜