I am trying to import as a dataframe a URL that has a JSON file in it.
import urllib.request, json
import pandas as pd
with urllib.request.urlopen("https://financialmodelingprep.com/api/v3/company-key-metrics/AAPL?period=quarter") as url:
data = json.loads(url.read().decode())
df = pd.DataFrame(data)
print(df)
It is not considering each metric in the JSON file as a column, but puts all the metrics under one column called "metrics"
while the output I am expecting is
Let's try this a couple of other ways
Option 1 using pd.read_json
:
pd.concat([pd.DataFrame(i, index=[0])
for i in
pd.read_json('https://financialmodelingprep.com/api/v3/company-key-metrics/AAPL?period=quarter')['metrics']],
ignore_index=True)
Option 2 using requests
:
import requests
resp = requests.get('https://financialmodelingprep.com/api/v3/company-key-metrics/AAPL?period=quarter')
txt = resp.json()
pd.DataFrame(txt['metrics'])
You can try this:
import urllib.request, json
import pandas as pd
from pandas.io.json import json_normalize
with urllib.request.urlopen('https://financialmodelingprep.com/api/v3/company-key-metrics/AAPL?period=quarter') as url:
data = json.loads(url.read().decode())
df = pd.DataFrame(json_normalize(data, 'metrics'))
print(df)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.