Home > Software design >  Read nested JSON dictionaries into pandas dataframe (Coin Market Cap API)
Read nested JSON dictionaries into pandas dataframe (Coin Market Cap API)

Time:05-25

I am trying to get a list of "stablecoins" from the coin market cap api in python. I am able to retrieve the json file that contains the data, but I am having a good deal of trouble pulling the information I need. the json file is below:

{'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'

The only info I need is the name. My code:

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)

Any help is appreciated!

CodePudding user response:

The json is cutted with some } and ] missing, I added those to get the expected result :

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'}]}}

As @LMD said in his comment, you can then use data as a dict like so :

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