Search code examples
pythonpython-3.xget

Writing only one response, why?


Trying to get get each response to save. So far it only prints all the responses and saves one. Please help. Edit: need help saving all the responses.

import requests
import json

url = 'https://www.virustotal.com/vtapi/v2/file/report'
resource = []
with open("/PATH/hashes.txt", "r") as f:
    for resource in f:
        print(resource)
        params = {'apikey': 'API KEY HERE', 'resource': resource}
        response = requests.get(url, params=params)
        response1 = response.json()
        print(response.json())
        with open('data.json', 'w') as J:
            json.dump(response1, J, indent=6)

Updated!! Thanks for all the help!

import requests
import json

url = 'https://www.virustotal.com/vtapi/v2/file/report'
params = {'apikey': 'API KEY HERE'}
resources = []
with open("/PATH/hashes.txt", "r") as f:
    for resource in f:
        print(resource)
        params['resource'] = resource
        response = requests.get(url, params=params)
        json_data = response.json()['sha256']
        print(json_data)
        resources.append(json_data)

with open('data.json', 'w') as J:
    json.dump(resources, J, indent=6)
J.close()
f.close()

Solution

  • import requests
    import json
    
    url = 'https://www.virustotal.com/vtapi/v2/file/report'
    params = {'apikey': 'API KEY HERE'}
    resources = []
    with open("/PATH/hashes.txt", "r") as f:
        for resource in f:
            print(resource)
            params['resource'] = resource
            response = requests.get(url, params=params)
            json_data = response.json()
            print(json_data)
            resources.append(json_data)
    
    with open('data.json', 'w') as f:
        json.dump(resources, f, indent=6)
    

    In your original code you overwrite data.json in each iteration of the loop. Append each JSON response to resources list (note the plural in the name - in your code you just overwrite the empty list by reusing name resource in the for loop). Then dump the list (it will be JSON array) into JSON file .