【问题标题】:API JSON result to file [closed]API JSON结果到文件[关闭]
【发布时间】:2021-03-11 03:33:09
【问题描述】:

我正在从 API 检索数据,但无法将其保存到文件中。

import requests
import json
response = requests.get(f'url', headers={'CERT': 'cert'})
response = response.json()

当我运行responserespons.json() 时,我可以看到我想要记录的数据。

我试过了:

str1 = ''.join(map(str, response))

with open('data.txt', mode ='a+') as f:
    f.write(f'{str1}') 
  
    print("File appended successfully") 
f.close()
str1 = ''.join(map(str, response))

with open('data.json', mode ='a+') as f:
    f.write(f'{str1}') 
  
    print("File appended successfully") 
f.close()
with open('data.json', mode ='a+') as results:
    result = json.loads(results)
    results.write(json.dumps(result, indent=4))
with requests.get(f'url', headers={'CERT': 'cert'}, stream=True) as r:
    r.raise_for_status()
    with open('data.json', 'wb') as f_out:
        for chunk in r.iter_content(chunk_size=8192): 
            f_out.write(chunk)
with open('data.txt', mode ='a+') as f:
    for items in response: 
        f.write('%s\n' % items) 
  
    print("File appended successfully") 
f.close()
with open('data.json', mode ='a+') as f:
    for items in response: 
        f.write('%s\n' % items) 
  
    print("File appended successfully") 
f.close()

还有其他一些没有运气的变体。有人可以指出我正确的方向或让我知道我做错了什么以从response 变量中获取数据以实际填充到文件中吗?

【问题讨论】:

标签: json python-3.x python-requests python-requests-json


【解决方案1】:

您可以使用json.dump(obj, fp) 将对象作为JSON 格式的流序列化为支持.write() 操作的文件对象fp

import json
with open('data.json', 'w') as fp:
    json.dump(your_json_response, fp)

【讨论】:

  • 感谢您的快速回复,但也没有运气。它不会抛出错误,所以看起来它已经完成,但它也不会写入文件。
  • 尝试打印 response.json() 并在可能的情况下将输出包含在您的帖子中。
【解决方案2】:

首先让我道歉,它一直困扰着我,我发现的代码都没有工作,尤其是没有错误。我跑了print(sys.path),发现我的输出没有去我想要的地方,它进入了一个完全不同的文件夹......所以它一直在工作,只是输出到一个我不知道为什么会这样的文件夹输出到。感谢大家的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多