将Json文件URL导入pandas数据框

5
我正在尝试将包含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)

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

而我期望的输出结果是:

进入图像描述这里

3个回答

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)

选项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'])

2
您可以尝试这样做:
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)

0

这对我来说很顺利

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)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接