python - Parsing json data and listing only large ones

Viewed 64

hello i am getting json data like below. I want it to list only "positionAmt" larger than 0.01 in the data I receive. Also, I cannot reach the element in the loop as below. can you help me ?

 def open_positions():
     positions = json.loads(client.futures_position_information())

     for x in positions:
         print(x['symbol'])
     return positions

json data

[
  {
    "symbol": "BNBUSDT",
    "positionAmt": "0.02",
    "entryPrice": "186.46100",
    "markPrice": "185.28100000",
    "unRealizedProfit": "-0.02360000",
    "liquidationPrice": "0",
    "leverage": "20",
    "maxNotionalValue": "250000",
    "marginType": "cross",
    "isolatedMargin": "0.00000000",
    "isAutoAddMargin": "false",
    "positionSide": "LONG",
    "notional": "3.70562000",
    "isolatedWallet": "0"
  },
  {
    "symbol": "BNBUSDT",
    "positionAmt": "0.00",
    "entryPrice": "0.00000",
    "markPrice": "185.28100000",
    "unRealizedProfit": "0.00000000",
    "liquidationPrice": "0",
    "leverage": "20",
    "maxNotionalValue": "250000",
    "marginType": "cross",
    "isolatedMargin": "0.00000000",
    "isAutoAddMargin": "false",
    "positionSide": "SHORT",
    "notional": "0",
    "isolatedWallet": "0"
  },
  {
    "symbol": "AKROUSDT",
    "positionAmt": "0",
    "entryPrice": "0.00000",
    "markPrice": "0.04434779",
    "unRealizedProfit": "0.00000000",
    "liquidationPrice": "0",
    "leverage": "20",
    "maxNotionalValue": "25000",
    "marginType": "isolated",
    "isolatedMargin": "0.00000000",
    "isAutoAddMargin": "false",
    "positionSide": "BOTH",
    "notional": "0",
    "isolatedWallet": "0"
  }
]
2 Answers

You can filter the output using list comprehensions:

filtered = [x for x in positions if float(x['positionAmt']) > 0.01]

This should return a list with the values where the value of positionAmt is larger than 0.01. You can tweak this to return a specific value, for example the symbol:

filtered_symbols = [x['symbol'] for x in positions if float(x['positionAmt']) > 0.01]

Is this want you want?

import json


def open_positions():
    with open("sample.json") as jf:
        positions = json.load(jf)
        return [x for x in positions if x["positionAmt"] > "0.01"]


print(open_positions())

Output:

[{'symbol': 'BNBUSDT', 'positionAmt': '0.02', 'entryPrice': '186.46100', 'markPrice': '185.28100000', 'unRealizedProfit': '-0.02360000', 'liquidationPrice': '0', 'leverage': '20', 'maxNo\ntionalValue': '250000', 'marginType': 'cross', 'isolatedMargin': '0.00000000', 'isAutoAddMargin': 'false', 'positionSide': 'LONG', 'notional': '3.70562000', 'isolate\ndWallet': '0'}]
Related