Rails Jbuilder: how to format an array of one item as a JSON array? -
i'm trying understand how utilize jbuilder methods inline in class. want forcefulness object array of length 1 match expected json spec.
here illustration of results want (note []
wrapping value associated sets
):
{ "sets": [{ "set_type": "default_set_type", "items": [ { "item_id": "ffff-0000-111", "quantity": "1" } ] }] }
here method far:
def to_3pl @shipment = self ... jbuilder.new |shipment| # how forcefulness jbuilder wrap single set []? shipment.sets shipment.set_type 'default_set_type' shipment.items @shipment.product_options |product| shipment.item_id product.product_id.to_s shipment.quantity product.quantity.to_s end end end end
and here json produced method (note value associated sets
not wrapped []
):
{ "sets": { "set_type": "default_set_type", "items": [ { "item_id": "ffff-0000-111", "quantity": "1" } ] } }
i've looked through jbuilder docs, , sure there's way this, can't seem figure out. syntax forcefulness jbuilder wrap single element []
in class method?
edit solution
many @dddd1919. here's updated method array wrapper implemented:
def to_3pl @shipment = self ... jbuilder.new |shipment| # forces jbuilder wrap object [] shipment.sets jbuilder.new.array!(['']) |set| shipment.set_type 'default_set_type' shipment.items @shipment.product_options |product| shipment.item_id product.product_id.to_s shipment.quantity product.quantity.to_s end end end end
if shipment.sets
list, can utilize jbuilder#array!
serialize info json array like:
def to_3pl @shipment = self ... jbuilder.new |shipment| # how forcefulness jbuilder wrap single set []? shipment.sets jbuilder.new.array!(shipment.sets) |set| .... end end end end
ruby-on-rails json jbuilder
No comments:
Post a Comment