使用Python请求和x-www-form-urlencoded发送嵌套的json数据

时间:2016-08-28 12:18:13

标签: python json python-requests

我无法弄清楚如何做到这一点。基本上一个特殊的API要求

'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'

但是他们希望表单数据是这样的:

stockLevels=[
  {
    "SKU": "sample string 1",
    "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
    "Level": 3
  },
  {
    "SKU": "sample string 1",
    "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
    "Level": 3
  }
]

我正在做的是:

def change_stock_quantity(self, SKU, qty):
    # Note that this will change quantity of just one item
    # instead of two like in the example above
    payload = {
        'stockLevels':[{
          'SKU': SKU,
          'LocationId': self.ebay1_location_id,
          'Level': qty,
        }]
    }
    r = self.session.post(self.session_server + '//api/Stock/SetStockLevel',
                  data=payload)

    print r.request.body
    # stockLevels=SKU&stockLevels=LocationId&stockLevels=Level
    # this is not correct, it should be something like:
    # stockLevels:[{"SKU":"P01", "LocationId":"00000000", "Level":4}]

    print r
    # <Response [400]> (obivously)

关于我做错什么的任何想法?

1 个答案:

答案 0 :(得分:1)

在挖掘出这个GitHub repo's examples后,他们的方法似乎如下:

  1. 身体确实是x-www-form-urlencoded
  2. 复杂参数是为x-www-form-urlencoded
  3. 编码的JSON字符串

    关注their PHP example来电CreateVariationGroup,请尝试以下方法:

    stockLevels=[
      {
        "SKU": "sample string 1",
        "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
        "Level": 3
      },
      {
        "SKU": "sample string 1",
        "LocationId": "de0f1890-0c49-4834-b8cd-8b766fba496a",
        "Level": 3
      }
    ]
    
    payload = {'stockLevels' : json.dumps(stockLevels)}
    
    # send payload encoded with x-www-form-urlencoded