我想從休息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"
}
你有什麼錯誤? – shazow
我得到'json.loads'的錯誤。這是它:'json.decoder.JSONDecodeError:期待值:第1行1列(字符0)' – Rachel
聽起來你下載不返回有效的JSON的URL。在不是JSON的東西上調用'json.loads(...)'是行不通的。將來,請在您的問題中包含錯誤。 :) – shazow