API JSON result to file

433 views Asked by At

I'm retrieving data from an API, but can not get it to save to a file.

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

When I run response or respons.json() I can see the data that I am wanting to record.

I have tried:

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()

And a few other variations with no luck. Can someone point me in the right direction or let me know what I'm doing incorrectly to get the data from the response variable to actually populate in the file?

2

There are 2 answers

2
Vishal Singh On BEST ANSWER

You can use json.dump(obj, fp) to serialize the object as a JSON formatted stream to a file object fp which supports .write() operation.

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

First let me apologize, it kept bugging me that none of the code I had found was working, especially with no error. I ran print(sys.path) and found that my output wasn't going where I wanted it, it was going into a completely different folder ... so it was working the whole time just outputting to a folder that I have no idea why it was outputting to. Thanks everyone for their help.