Home > other >  I am getting an error: new_data.append(i["metadata"]) KeyError: 'metadata'
I am getting an error: new_data.append(i["metadata"]) KeyError: 'metadata'

Time:04-14

**I was trying to extract live data from solscan website enter image description here

CodePudding user response:

KeyError is called when something in a dictionary doesn't exist. In this case 'metadata' is not a Key in the dictionary. Here is the updated code:

import requests
import json
import pandas as pd
pd.set_option('display.max_row',None)
pd.set_option('display.max_column',None)
pd.set_option('display.width',None)

class Solscanner:
    def __init__(self):
        self.headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0'}
        self.session = requests.Session()
        self.session.get("https://solscan.io",headers=self.headers)

def pre_nft_data(self):
    params={
        "offset":0,
        "limit":50
    }
    data = self.session.get(f"https://api.solscan.io/nft/market/trade",
    headers=self.headers,params=params)#.json["data"]
    data=list(json.loads(data.content.decode())['data'])
    new_data = []
    for i in data:
        new_data.append(i)
    df=pd.DataFrame(new_data)
    #return list(df['symbol])
    return df
nft=Solscanner()
print(nft.pre_nft_data())

NOTE: The output will be a bit jumbled.

CodePudding user response:

You can do something like this to append only when metadata is present.

        for i in data:
            meta = i.get("metadata")
            if meta:
                new_data.append(meta)
  • Related