繁体   English   中英

如何从Rest API获取数据并将JSON保存到txt文件?

[英]How to get data from rest api and save JSON to txt file?

我正在尝试从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"
      }

听起来您正在尝试json.load(...)实际上不是JSON的东西。

查看正在使用的URL, https://jsonplaceholder.typicode.com/返回HTML而不是JSON。

如果您使用类似https://jsonplaceholder.typicode.com/posts方法返回JSON,则该特定错误应消失。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM