Search code examples
pythonjsonurllib

How to access list of json-like objects from web api?


Just a side project I'm doing right now playing around with covid19 api. And I was hoping for something that would let me access the data with something like data2.countries.

import requests as r
import urllib
import json

url = 'https://api.covid19api.com/total/dayone/country/south-africa'
foo = urllib.request.urlopen(url)
data = json.loads(foo.read().decode())
data2 = json.parse(data)
print(data2)

The data looks like this - it's all in one list:

[{'Country': 'South Africa', 'CountryCode': '', 'Province': '', 'City': '', 'CityCode': '', 'Lat': '0', 'Lon': '0', 'Confirmed': 607045, 'Deaths': 12987, 'Recovered': 504127, 'Active': 89931, 'Date': '2020-08-22T00:00:00Z'},
 {'Country': 'South Africa', 'CountryCode': '', 'Province': '', 'City': '', 'CityCode': '', 'Lat': '0', 'Lon': '0', 'Confirmed': 609773, 'Deaths': 13059, 'Recovered': 506470, 'Active': 90244, 'Date': '2020-08-23T00:00:00Z'}]

So far I'm getting:

  File "~/20200813file/main.py", line 19, in <module>
    data2 = json.parse(data)

AttributeError: module 'json' has no attribute 'parse'

Solution

  • Why not try converting it into a pandas Dataframe.

    import urllib
    import json
    import pandas as pd
    
    url = 'https://api.covid19api.com/total/dayone/country/south-africa'
    
    
    foo = urllib.request.urlopen(url)
    
    data = json.loads(foo.read().decode())
    
    df = pd.DataFrame(data)
    
    print(df.Country)