将 Json 文件 URL 导入 pandas 数据框

Mic*_*ssi 5 python json pandas

我正在尝试将其中包含 JSON 文件的 URL 作为数据框导入。

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)
Run Code Online (Sandbox Code Playgroud)

它不会将 JSON 文件中的每个指标视为一列,而是将所有指标放在名为“metrics”的一列下

而我期望的输出是

在此输入图像描述

Sco*_*ton 4

让我们尝试其他几种方法

选项 1 使用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)
Run Code Online (Sandbox Code Playgroud)

选项 2 使用requests

import requests

resp = requests.get('https://financialmodelingprep.com/api/v3/company-key-metrics/AAPL?period=quarter')
txt = resp.json()
pd.DataFrame(txt['metrics'])
Run Code Online (Sandbox Code Playgroud)