2016-11-26 76 views
0

我想從休息api獲取一些數據並將JSON保存到txt文件。這是我做的:如何從rest api獲取數據並將JSON保存到txt文件?

#random rest api 
a = 'https://thiswouldbemyurl.com' 

#urllib3 + poolmanager for requests 
import urllib3 
http = urllib3.PoolManager() 

import json 
r = http.request('GET', a) 
json.loads(r.data.decode('utf-8')) 

with open('data.txt', 'w') as f: 
    json.dump(data, f, ensure_ascii=False) 

我得到一個錯誤已經與json.load。我究竟做錯了什麼?

編輯:這是JSON的樣子

{ 
    "success":true, 
    "data":[ 
     { 
     "id":26, 
     "name":"A", 
     "comment":"", 
     "start_time_plan":null, 
     "start_time_actual":"2016-09-13 00:00:00", 
     "start_time_delta":null, 
     "start_time_score":null, 
     "start_time_score_achievement":null, 
     "start_time_traffic_light":null, 
     "end_time_plan":null, 
     "end_time_actual":"2016-09-13 00:00:00", 
     "end_time_delta":null, 
     "end_time_score":null, 
     "end_time_score_achievement":null, 
     "end_time_traffic_light":null, 
     "status":0, 
     "measure_schedule_revision_id":63, 
     "responsible_user_id":3, 
     "created_time":"2016-09-13 11:29:14", 
     "created_user_id":3, 
     "modified_time":"2016-09-21 16:33:41", 
     "modified_user_id":3, 
     "model":"Activity" 
     } 
+0

你有什麼錯誤? – shazow

+0

我得到'json.loads'的錯誤。這是它:'json.decoder.JSONDecodeError:期待值:第1行1列(字符0)' – Rachel

+1

聽起來你下載不返回有效的JSON的URL。在不是JSON的東西上調用'json.loads(...)'是行不通的。將來,請在您的問題中包含錯誤。 :) – shazow

回答

1

這聽起來像你想json.load(...)的東西,實際上不是JSON。

縱觀URL你使用,https://jsonplaceholder.typicode.com/返回HTML而不是JSON。

如果您使用類似https://jsonplaceholder.typicode.com/posts其中確實返回JSON,那麼該特定的錯誤應該消失。

+0

對不起,我只是使用了一個隨機的URL。我確實得到了一個JSON(見上面的編輯)。這裏可能是什麼問題? – Rachel

相關問題