简体   繁体   中英

Importing Json File URL to pandas data frame

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)

This worked smooth for me

import requests
import pandas as pd

resp = requests.get('https://api.binance.com/api/v3/ticker/24hr', timeout=10,headers={'Content-Type': 'application/json'})
df= pd.read_json(resp.text)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM