2017-08-09 82 views
0

我有一個使用請求模塊將JSON發佈到API的Python腳本。但是,我發佈了一個使用十六進制的散列。我快到的時候我用下面的代碼中的錯誤:JSON中帶前導零的字符串?

r = requests.post('apiurl.com/do/stuff', json={"key": '0052ccca'}) 

的響應是一個400錯誤:

{"message": "Could not parse request body into json: Unrecognized token 
\'k0052ccca\': was expecting (\'true\', \'false\' or \'null\')\n at 
[Source: [[email protected]; line: 2, column: 23]"} 

this answer的建議是把前導零的字符串,但我已經這樣做了,仍然出現錯誤。

回答

4
>>> import requests 
>>> response = requests.post('http://httpbin.org/post', json={"key": '0052ccca'}) 
>>> print(response.text) 
{ 
    "args": {}, 
    "data": "{\"key\": \"0052ccca\"}", 
    "files": {}, 
    "form": {}, 
    "headers": { 
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "19", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.3" 
    }, 
    "json": { 
    "key": "0052ccca" 
    }, 
    "origin": "38.98.147.133", 
    "url": "http://httpbin.org/post" 
} 

沒有什麼錯解碼時json,你可以看到它是由請求正確編碼:

>>> response.request.body 
b'{"key": "0052ccca"}' 

所以問題是服務器端(或您的示例代碼是太不一樣了你真正的代碼來揭示真正的問題)。

相關問題