Search code examples
ruby-on-railsjbuilder

How do I suppress empty arrays from json created using jbuilder


I have the following ruby code in _schema.json.jbuilder

json.member_of @dispenser.organizations do |organization|
  json.set! "@type", "Organization"
  json.name organization.name
end

The problem is in the generated json when a dispenser has no organizations:

"memberOf":[]

Can jbuilder handle this (using a configuration setting), or should I just wrap the whole thing in a conditional like if @dispenser.organizations.present?


Solution

  • You ought to be able to set:

    json.ignore_nil!
    

    And on arrays, use:

    member_of.presence
    

    An empty array should be converted to nil, and then ignored.