0

我需要创建多个“项目”以在 json 请求中使用。

这是一个有效的请求:

customs_info = EasyPost::CustomsInfo.create(
        eel_pfc: 'NOEEI 30.37(a)',
        customs_certify: true,
        customs_signer: "first_name last_name",
        contents_type: 'merchandise',
        contents_explanation: '',
        restriction_type: 'none',
        restriction_comments: '',
        # non_delivery_option: 'abandon',
        customs_items: [
          {
          description: "asdf",
          quantity: 1,
          weight: 23,
          value: 23,
          # hs_tariff_number: '654321',
          origin_country: 'US'
          },
          {
          description: "1234568",
          quantity: 1,
          weight: 23,
          value: 23,
          # hs_tariff_number: '654321',
          origin_country: 'US'
          }
        ]
      )

我需要的是不需要手动设置customs_items.

我试过了:

customs_info = EasyPost::CustomsInfo.create(
        eel_pfc: 'NOEEI 30.37(a)',
        customs_certify: true,
        customs_signer: "#{shipping_address.shipping_address_final.first_name} #{shipping_address.shipping_address_final.last_name}",
        contents_type: 'merchandise',
        contents_explanation: '',
        restriction_type: 'none',
        restriction_comments: '',
        # non_delivery_option: 'abandon',
        customs_items: [
        vendor_line_items.map do |li|
          {
          description: "#{li.shop_product.product.item.title}",
          quantity: li.quantity,
          weight: li.shop_product.product.weight,
          value: li.shop_product.price,
          # hs_tariff_number: '654321',
          origin_country: 'US'
          }
        end
        ]
      )

错误声明:创建自定义项目的参数无效或丢失

如何创建循环以处理 JSON 请求并像第一个手动工作的示例一样工作?

4

1 回答 1

0

如果您删除代码[]周围的内容vendor_line_itmes.map,您将很高兴。

customs_info = EasyPost::CustomsInfo.create(
    # ...
    customs_items: vendor_line_items.map do |li|
        {
            description: "#{li.shop_product.product.item.title}",
            quantity: li.quantity,
            # ...
        }
    end
    )

map 操作返回一个数组,因此您当前生成的 json 看起来像(注意 custom_info 中的数组数组):

{ 
    "eel_pfc": "NOEEI 30.37(a)",
    ...

    "customs_info": [
        [
            {
                "description": "...",
                "quantity": 5,
                ...
            }
        ]
    ]
}
于 2019-08-15T12:45:15.693 回答