API JSON 结果归档

API JSON result to file

我正在从 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.dump(obj, fp) 将对象作为 JSON 格式的流序列化为支持 .write() 操作的文件对象 fp

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

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