NameError: name 'test_result' is not defined

Hi there! I wrote the code below but getting the following error:
NameError: name ‘test_result’ is not defined

#Code starts here

import requests
import csv
import pandas as pd
import json # added code

result = requests.get(‘https://bioportal.salud.gov.pr/api/administration/reports/minimal-info-unique-tests’)
print(result.status_code)

copied from the post

data_file = open(‘test_results_covidpr.csv’, ‘w’)
csv_writer = csv.writer(data_file)

header = test_result.keys()
csv_writer.writerow(header)

for test_result in result.json()[:5]:
csv_writer.writerow(test_result.values())

data_file.close()

code ends here

You did not specify what exactly you intend to achieve with your code.

I ran the code below to convert the json object into a dataframe.

If you want your final data in csv format, you can convert using df.to_csv().

The data has this shape (295195, 7), which is a lot of rows. Having it has a dataframe might be better.

import requests
import csv
import pandas as pd
import json # added code

result = requests.get('https://bioportal.salud.gov.pr/api/administration/reports/minimal-info-unique-tests')
print(result.status_code)         #200

data = result.json()   # Converts the json file to a list of dictionaries

type(data)         # List

df = pd.DataFrame(data)   # Convert data into a dataframe

1 Like

Thank you so much for your help. Yes, you’re right. My final objective is to convert it into a .csv Thank you for the advice of keeping it as DataFrame. :+1: I will do

1 Like