skip to Main Content

I would like to print only objects that contain USDT from:

requestT = requests.get('https://api1.binance.com/api/v3/ticker/price')
json_data = json.loads(requestT.text)
print(json_data)

Example:

data = [{'symbol': 'BNBETH', 'price': '0.16540000'}, {'symbol': 'BTCUSDT', 'price': '64321.11000000'}, {'symbol': 'ETHUSDT', 'price': '3330.76000000'}]

Result:

data1 = [{'symbol': 'BTCUSDT', 'price': '64321.11000000'}, {'symbol': 'ETHUSDT', 'price': '3330.76000000'}]

3

Answers


  1. You can filter the data for example with list-comprehension:

    import requests
    
    json_data = requests.get("https://api1.binance.com/api/v3/ticker/price").json()
    
    usdt_data = [d for d in json_data if "USDT" in d["symbol"]]
    print(*usdt_data, sep="n")
    

    Prints:

    ...
    
    {'symbol': 'PDAUSDT', 'price': '0.12620000'}
    {'symbol': 'AXLUSDT', 'price': '1.88250000'}
    {'symbol': 'WIFUSDT', 'price': '2.26590000'}
    {'symbol': 'METISUSDT', 'price': '97.19000000'}
    {'symbol': 'AEVOUSDT', 'price': '2.39000000'}
    {'symbol': 'BOMEUSDT', 'price': '0.01351400'}
    {'symbol': 'ETHFIUSDT', 'price': '4.02700000'}
    
    Login or Signup to reply.
  2. Always ensure that your HTTP request succeeded before trying to do anything with the response.

    You could use a lambda for this but my preference is a discrete function.

    So…

    import requests
    
    def usdt(d):
        return "USDT" in d.get("symbol", "")
    
    with requests.get("https://api1.binance.com/api/v3/ticker/price") as response:
        response.raise_for_status()
        result = list(filter(usdt, response.json()))
        print(result)
    
    Login or Signup to reply.
  3. based on your hoped for result, I wrote a fairly simple solution, where I create a new list containing the matches inside it, in the code I also commented the various steps for a better understanding, obviously there are many ways to obtain the same result, this method is the most basic

    Code.py

    import json
    
    data = [{'symbol': 'BNBETH', 'price': '0.16540000'}, {'symbol': 'BTCUSDT', 'price': '64321.11000000'}, {'symbol': 'ETHUSDT', 'price': '3330.76000000'}]
    
    new_data = []
    
    for usdt in data:
        
        # here you check if "USDT" is inside the "symbol" key of each result
        
        if 'USDT' in usdt['symbol']:
            
            # if it exists, I insert every single match into the new list
            new_data.append(usdt)
            
    
    # I call the output with indent=4 for better reading
    
    print(json.dumps(new_data, indent=4))
    

    result:

    [
        {
            "symbol": "BTCUSDT",
            "price": "64321.11000000"
        },
        {
            "symbol": "ETHUSDT",
            "price": "3330.76000000"
        }
    ]
    

    I hope I have been of help to you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search