簡體   English   中英

將嵌套的 JSON 字典讀入 pandas 數據框(Coin Market Cap API)

[英]Read nested JSON dictionaries into pandas dataframe (Coin Market Cap API)

我正在嘗試從 python 中的硬幣市值 api 獲取“穩定幣”列表。 我能夠檢索包含數據的 json 文件,但是在提取所需信息時遇到了很多麻煩。 json文件如下:

{'status': {'timestamp': '2022-05-24T15:27:33.221Z', 'error_code': 0, 'error_message': None, 'elapsed': 25, 'credit_count': 2, 'notice': None}, 'data': {'id': '604f2753ebccdd50cd175fc1', 'name': 'Stablecoin', 'title': 'Stablecoin', 'description': 'Stablecoin', 'num_tokens': 99, 'last_updated': '2021-11-10T11:25:48.501Z', 'avg_price_change': -0.9522605162637363, 'market_cap': 159395366765.37, 'market_cap_change': -0.5842274725274725, 'volume': 69946658004.58846, 'volume_change': 89.59030769230768, 'coins': [{'id': 825, 'name': 'Tether', 'symbol': 'USDT'

我需要的唯一信息是名稱。 我的代碼:

import pandas as pd
import json

url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/category'

parameters = {
    'id': '604f2753ebccdd50cd175fc1',
    'start': '1',
    'limit': '10',
    'convert': 'USD'
}
headers = {
    'Accepts': 'application/json',
    'X-CMC_PRO_API_KEY': API_KEY,
}

resp = requests.get(url, params=parameters, headers=headers)
jsondata = json.loads(resp.text)
print(jsondata)
CoinDF = pd.json_normalize(jsondata['data']['coins'])
print(CoinDF)

任何幫助表示贊賞!

json 被一些}]刪減,我添加了這些以獲得預期的結果:

data = {'status': 
        {'timestamp': '2022-05-24T15:27:33.221Z', 'error_code': 0, 'error_message': None, 'elapsed': 25, 'credit_count': 2, 'notice': None}, 
         'data': {'id': '604f2753ebccdd50cd175fc1', 'name': 'Stablecoin', 'title': 'Stablecoin', 'description': 'Stablecoin', 'num_tokens': 99, 'last_updated': '2021-11-10T11:25:48.501Z', 'avg_price_change': -0.9522605162637363, 'market_cap': 159395366765.37, 'market_cap_change': -0.5842274725274725, 'volume': 69946658004.58846, 'volume_change': 89.59030769230768, 'coins': [{'id': 825, 'name': 'Tether', 'symbol': 'USDT'}]}}

正如@LMD 在他的評論中所說,您可以像這樣使用data作為dict

>>> data['data']['coins'][0]['name']
'Tether'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM