Rails Jbuilder: how to format a single item array as a JSON array?

I am trying to figure out how to use Jbuilder inline methods in a class. I want an object into an array of length one to conform to the expected JSON specification.

Here's an example of the results I want (note the []

wrapping around the value associated with sets

):

{
  "sets": [{
    "set_type": "default_set_type",
    "items": [
      {
        "item_id": "FFFF-0000-111",
        "quantity": "1"
      }
    ]
  }]
}

      

Here's my method:

def to_3pl
  @shipment = self
  ...
  Jbuilder.new do |shipment|

    # How do I force jbuilder to wrap a single set with []?
    shipment.sets do
      shipment.set_type 'default_set_type'
      shipment.items @shipment.product_options do |product|
        shipment.item_id product.product_id.to_s
        shipment.quantity product.quantity.to_s
      end
    end
  end
end

      

And here is the JSON generated by my method (note that the value associated with sets

is not wrapped []

):

{
  "sets": {
    "set_type": "default_set_type",
    "items": [
      {
        "item_id": "FFFF-0000-111",
        "quantity": "1"
      }
    ]
  }
}

      

I've looked at the Jbuilder docs and I'm sure there is a way to do this, but I can't seem to get it out of the way. What is the syntax to force Jbuilder to wrap a single element using []

in a class method?

EDIT WITH SOLUTION

Thanks a lot @ dddd1919. Here's a successfully implemented updated method with an array wrapper:

def to_3pl
  @shipment = self
  ...
  Jbuilder.new do |shipment|

    # Forces jbuilder to wrap the object with []
    shipment.sets Jbuilder.new.array!(['']) do |set|
      shipment.set_type 'default_set_type'
      shipment.items @shipment.product_options do |product|
        shipment.item_id product.product_id.to_s
        shipment.quantity product.quantity.to_s
      end
    end
  end
end

      

+3


source to share


1 answer


If shipment.sets

is a list, you can use Jbuilder#array!

to serialize the data in a json array like:



def to_3pl
  @shipment = self
  ...
  Jbuilder.new do |shipment|

    # How do I force jbuilder to wrap a single set with []?
    shipment.sets do
      Jbuilder.new.array!(shipment.sets) do |set|
        ....
      end
    end
  end
end

      

+3


source







All Articles