2016-11-24 73 views
0

我正在嘗試閱讀JSON後,我與urllib2發送url請求。readingJSON with simplejson python

我的代碼:

request = urllib2.Request("https://127.0.0.1:443/myAPI", data=form_data, headers=headers) 
response = urllib2.open(request) 

所以,問題是當我試圖從響應對象讀取JSON。 我做它這樣

simplejson.loads(response.read()) 

我得到的錯誤是:當我送我的Firefox瀏覽器的請求

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/opt/new/main3/python/simplejson/__init__.py", line 385, in loads 
    return _default_decoder.decode(s) 
    File "/opt/new/main3/python/simplejson/decoder.py", line 402, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "/opt/new/main3/python/simplejson/decoder.py", line 420, in raw_decode 
    raise JSONDecodeError("No JSON object could be decoded", s, idx) 
simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0) 

有趣的部分是,我打字地址127.0.0.1/myAPI在url線,我得到了屏幕上的json,我可以在調試模式下看到它作爲JSON {「hosts」:[{「host」:「127.0.0.1: 4448「}]}

所以JSON是有效的..

在調試我得到這個頁面:

<!DOCTYPE html> 
<html> 
<head> 
    <!-- framebusting --> 
    <style> 
     html{display : none ;} 
    </style> 
    <script type="text/javascript"> 
     if (self == top) { 
      document.documentElement.style.display = "block"; 
     } else { 
      top.location = self.location; 
     } 
    </script> 
    <script type="text/javascript" src="js/detectBrowser.js"></script> 
    <meta charset="utf-8"/> 
    <link rel="StyleSheet" href="css/forensics.css" type="text/css" media="screen"/> 
</head> 
<body> 
    <script type="text/javascript" src="libs/requirejs/require.js" data-main="js/login.js"></script> 
</body> 
</html> 

是任何一個有一些方法來解決這個問題,或者我怎麼能直接從讀取JSON文本在響應對象,甚至看,在調試

我很欣賞螞蟻的幫助,我試圖爲至少3天來弄明白 感謝

+0

嘗試打印什麼是響應,以檢查它是否與瀏覽器通過執行print response.read()並在此處發佈結果。也有可能返回的字符串有一些不可見的控制字符,您的瀏覽器不顯示但使simplejson失敗。 <!DOCTYPE HTML> – Antoine

+0

<! - framebusting - > <腳本類型= 「文本/ JavaScript的」> 如果(個體==頂部) document.documentElement.style.display =「block」; } else { top.location = self.location; } – yntnm

+0

<腳本類型= 「文本/ JavaScript的」 SRC = 「JS/detectBrowser.js」> <元的charset = 「utf-8」/> <鏈路的rel = 「樣式表的」 href =「CSS/forensics.css「type =」text/css「media =」screen「/> yntnm

回答

0

所以這是我的壞和API是需要一個coockie。 添加cookie頭後我收到一個正確的JSON

0

我想這是因爲這個simplejson.loads(response .read())的。你有

響應和.read()之間的空間嘗試以下操作:

request = urllib2.Request("https://127.0.0.1:443/myAPI", data=form_data, headers=headers) 
response = urllib2.open(request) 
response_body = response.read() 
response_body_json = simplejson.loads(response_body) 
+0

no ...在我沒有的真實代碼中,我在這裏修復它也 – yntnm