【问题标题】:How to create loop within a JSON request object?如何在 JSON 请求对象中创建循环?
【发布时间】:2019-12-21 15:13:28
【问题描述】:

我需要创建多个“项目”以在 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 请求并像第一个手动工作的示例一样工作?

【问题讨论】:

  • map 已经返回一个数组。删除它周围的方括号。 customs_items: vendor_line_items.map ....
  • 你最棒了

标签: ruby-on-rails arrays json ruby easypost


【解决方案1】:

如果您删除 [] 周围的 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,
                ...
            }
        ]
    ]
}

【讨论】:

    猜你喜欢
    • 2016-11-11
    • 2013-06-10
    • 1970-01-01
    • 2015-10-14
    • 2023-03-28
    • 2011-01-07
    • 2020-08-01
    • 2015-02-04
    相关资源
    最近更新 更多