2016-11-26 51 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

相关问题