2015-06-19 75 views
0

我正在使用JSON庫並嘗試將頁面訂閱源導入到CSV文件。嘗試許多方法來獲得結果,但每次執行代碼時都給予JSON不可串行化。沒有Facebook使用我已經使用過的授權碼,因此連接字符串將會改變,但是如果您使用具有公共隱私的頁面,您仍然可以從下面的代碼中獲得結果。JSON序列化Python 3.2中的錯誤

以下是代碼

import urllib3 
import json 
import requests 
#from pprint import pprint 
import csv 
from urllib.request import urlopen 

page_id = "abcd" # username or id 
api_endpoint = "https://graph.facebook.com" 
fb_graph_url = api_endpoint+"/"+page_id 
try: 
#api_request = urllib3.Requests(fb_graph_url) 
    #http = urllib3.PoolManager() 
    #api_response = http.request('GET', fb_graph_url) 
    api_response = requests.get(fb_graph_url) 
    try: 
     #print (list.sort(json.loads(api_response.read()))) 
     obj = open('data', 'w') 
     # write(json_dat) 
     f = api_response.content 

     obj.write(json.dumps(f)) 
     obj.close() 
    except Exception as ee: 
     print(ee) 
except Exception as e: 
    print(e) 

試了很多辦法,但沒有成功。希望有人能幫到

+0

你所得到的網頁源不是JSON –

回答

0
requests.get(fb_graph_url).content 

可能是一個字符串。使用json.dumps就行不通了。該函數需要列表或字典作爲參數。

如果請求已經返回JSON,只需將其寫入文件。

+0

感謝,但沒有決心嘗試過。 –

1

api_response.content是API的文本內容,而不是Python對象,因此您將無法轉儲它。

嘗試之一:

f = api_response.content 
obj.write(f) 

或者

f = api_response.json() 
obj.write(json.dumps(f)) 
+0

當然會嘗試和更新。 –

+0

試過提供的解決方案但是獲得的必須是str,而不是字節,'字節'對象沒有屬性'json'沒有解析 –

+0

你能打開一個交互式會話並打印api_response.content的內容嗎? –