2017-06-02 33 views
0

我有以下代碼:在JSON有效載荷中傳遞變量?

import requests 
import time 

orderID = time.strftime("%#d%m%y") + str(randint(10, 99)) 
payload = '{ "id": 62345, "shippingCharge": 0.0, "giftCharge": 0.0, "amountDue": 13000.0}' 
url = "test.com/v1/%s".format(orderID) 
s = requests.Session() 
s.headers.update({'Content-Type': 'application/json'}) 
r = s.post(url , payload, auth=('test01', 'test01')) 

我想通過在下面的可變orderID

  1. 如JSON有效載荷id字段的值。
  2. 在URL字符串v1

請幫助我。

+0

請發表您的實際代碼。這是無效的 – e4c5

+0

編輯問題 – e4c5

+0

http://stackoverflow.com/help/how-to-ask – e4c5

回答

0

1)作爲JSON負載中id字段的值。

orderID = time.strftime("%#d%m%y") + str(randint(10, 99)) 
payload = '{ "id": '+ str(orderID) +', "shippingCharge": 0.0, "giftCharge": 0.0, 
"amountDue": 13000.0}' 

2)在URL字符串

你給的代碼V1之後是爲您的使用情況下是正確的。

+0

收到此錯誤使用上述代碼 – mach

+0

文件 「saveOrder.py」,第17行之後,在 打印(r.json()) 文件「d:\ Python的\ LIB \站點包\請求\車型。 py「,第866行,在json 返回complexjson.loads(self.text,** kwargs) 加載中的文件」D:\ Python \ lib \ json \ __ init__.py「,第354行 return _default_decoder.decode s) 文件「D:\ Python \ lib \ json \ decoder.py」,行339,解碼爲 obj,end = self.raw_decode(s,idx = _w(s,0).end()) – mach

+0

File 「D:\ Python \ lib \ json \ decoder.py」,第357行,在raw_decode中 從無引發JSONDecodeError(「Expecting value」,s,err.value)json.decoder.JSONDecodeError:Expecti ng值:第1行第1列(char 0) – mach

0

我認爲這將工作:

import requests 
from random import randint 
import time 

orderID = time.strftime("%#d%m%y") + str(randint(10, 99)) 
payload = ('{ "id": ' + str(orderID) + ', "shippingCharge": 0.0, "giftCharge": 0.0, ' 
      '"amountDue": 13000.0}') 
url = "test.com/v1/{}".format(orderID) 
s = requests.Session() 
s.headers.update({'Content-Type': 'application/json'}) 
r = s.post(url , payload, auth=('test01', 'test01')) 
+0

此代碼引發上述錯誤 – mach

+0

嘗試使用'r = s.post(url,data = payload,auth =('test01','test01'))'最後一行。如果這不起作用,請嘗試'r = s.post(url,json = payload,auth =('test01','test01'))''。 – martineau

+0

@mach什麼錯誤? – crazyglasses