import requests
import pandas as pd
import APIKEY
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
parameters = {
'start': '1',
'limit': '10',
'convert': 'USD'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': APIKEY.KeyAPI,
}
jsondata = requests.get(url, params=parameters, headers=headers).json()
CoinDF = pd.read_json(jsondata)
CoinDF.to_csv(r'/home/USER/Documents/CoinData.csv')
我试图让 Pandas 读取 API 返回的 JSON 数据,但是当我运行这个程序时,我得到了这个错误
Traceback (most recent call last):
File "/home/crow/PycharmProjects/CoinTracker/CoinMarketCapAPI.py", line 24, in <module>
CoinDF = pd.read_json(jsondata, orient='index')
File "/home/crow/PycharmProjects/CoinTracker/venv/lib/python3.8/site-packages/pandas/util/_decorators.py", line 199, in wrapper
return func(*args, **kwargs)
File "/home/crow/PycharmProjects/CoinTracker/venv/lib/python3.8/site-packages/pandas/util/_decorators.py", line 299, in wrapper
return func(*args, **kwargs)
File "/home/crow/PycharmProjects/CoinTracker/venv/lib/python3.8/site-packages/pandas/io/json/_json.py", line 540, in read_json
json_reader = JsonReader(
File "/home/crow/PycharmProjects/CoinTracker/venv/lib/python3.8/site-packages/pandas/io/json/_json.py", line 622, in __init__
data = self._get_data_from_filepath(filepath_or_buffer)
File "/home/crow/PycharmProjects/CoinTracker/venv/lib/python3.8/site-packages/pandas/io/json/_json.py", line 659, in _get_data_from_filepath
self.handles = get_handle(
File "/home/crow/PycharmProjects/CoinTracker/venv/lib/python3.8/site-packages/pandas/io/common.py", line 558, in get_handle
ioargs = _get_filepath_or_buffer(
File "/home/crow/PycharmProjects/CoinTracker/venv/lib/python3.8/site-packages/pandas/io/common.py", line 371, in _get_filepath_or_buffer
raise ValueError(msg)
ValueError: Invalid file path or buffer object type: <class 'dict'>
与 API 的连接正常,但由于某种原因,我无法让 Pandas 读取它提供的内容。
谢谢您的帮助
编辑:
所以我对它做了一些修改,我认为挂断是 JSON 文件的结构。
它似乎是一个字典列表,但其中至少有一组嵌套字典。像这样...
[string1{blah:blah},string2{blah:blah,blah:blah,Nest{nest1:nest2}}]
. 当我刚刚尝试将它从 JSON 读取到数据框时,我认为它在第二级字典中被阻塞了。我想现在的问题是如何在 Pandas 中使嵌套的字典键成为自己的列
编辑 2:由于某种原因,JSON 文件使用单引号而不是双引号,我认为这把一切都搞砸了。如果有人有一个好的答案,我会留下这个问题,但我不确定是否有一个好的解决方案。
最终编辑:
import requests
import pandas as pd
import KeyStuff
import json
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
parameters = {
'start': '1',
'limit': '10',
'convert': 'USD'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': KeyStuff.APIKey,
}
resp = requests.get(url, params=parameters, headers=headers)
jsondata = json.loads(resp.text)
CoinDF = pd.json_normalize(jsondata['data'])
CoinDF.to_csv("C:\\Users\\USER\\Documents\\Junk\\CMCAPIDF.csv")
这是最终的功能代码。非常感谢乔纳森·莱昂!