【问题标题】:How can I set a condition for a JSON file?如何为 JSON 文件设置条件?
【发布时间】:2021-12-07 17:56:56
【问题描述】:

我正在尝试编写一个程序来读取 JSON 文件并从中获取我需要的信息。在我的 JSON 文件中有一个参数:'exchangeId',它输出交换号。我想确保只有我设置的那些交换,或者更确切地说他们的'exchangeId',记录在我的字典中,如果硬币在列表中没有任何'exchangeId',这个硬币不想保存为 JSON文件。我该怎么做?

我的代码:

response = s.get(url=url, headers=headers).json()
json_data = response['data']
pairs = []
out_object = {}

for pair in json_data["marketPairs"]:
    pairs.append({
        "exchange_name": pair["exchangeName"],
        "market_url": pair["marketUrl"],
        "price": pair["price"],
        "last_update" : pair["lastUpdated"],
        "exchange_id": pair["exchangeId"] # That ids what I'm would to have
                                          # 102,311,200,302,521,433,482,406,42,400
        })

out_object["name_of_coin"] = json_data["name"]
out_object["marketPairs"] = pairs
out_object["pairs"] = json_data["numMarketPairs"]

JSON 文件:

{
    "name_of_coin": "yearn.finance",
    "marketPairs": [
        {
            "exchange_name": "Binance",
            "market_url": "https://www.binance.com/en/trade/YFI_USDT",
            "price": 24087.947333328204,
            "last_update": "2021-12-07T17:49:54.000Z",
            "exchange_id": 270
        },
        {
            "exchange_name": "FTX",
            "market_url": "https://ftx.com/trade/YFI/USD",
            "price": 24110.0,
            "last_update": "2021-12-07T17:49:53.000Z",
            "exchange_id": 524
        },
        {
            "exchange_name": "Coinbase Exchange",
            "market_url": "https://pro.coinbase.com/trade/YFI-USD",
            "price": 24085.37,
            "last_update": "2021-12-07T17:48:57.000Z",
            "exchange_id": 89
        },
        {
            "exchange_name": "Huobi Global",
            "market_url": "https://www.huobi.com/en-us/exchange/yfi_usdt",
            "price": 24096.582498139305,
            "last_update": "2021-12-07T17:49:53.000Z",
            "exchange_id": 102
        },
        {
            "exchange_name": "Bybit",
            "market_url": "https://www.bybit.com/en-US/trade/spot/YFI/USDT",
            "price": 24045.551976080656,
            "last_update": "2021-12-07T17:48:10.000Z",
            "exchange_id": 521
        },
        {
            "exchange_name": "FTX",
            "market_url": "https://ftx.com/trade/YFI/USDT",
            "price": 24079.402222379562,
            "last_update": "2021-12-07T17:49:53.000Z",
            "exchange_id": 524
        },
        {
            "exchange_name": "Binance",
            "market_url": "https://www.binance.com/en/trade/YFI_BTC",
            "price": 24090.344540422568,
            "last_update": "2021-12-07T17:49:54.000Z",
            "exchange_id": 270
        },
        {
            "exchange_name": "Bithumb",
            "market_url": "https://www.bithumb.com/trade/order/YFI_KRW",
            "price": 25285.64198822739,
            "last_update": "2021-12-07T17:49:53.000Z",
            "exchange_id": 200
        },
        {
            "exchange_name": "Gemini",
            "market_url": "https://gemini.com/",
            "price": 24088.85,
            "last_update": "2021-12-07T17:49:55.000Z",
            "exchange_id": 151
        },
        {
            "exchange_name": "Bitfinex",
            "market_url": "https://www.bitfinex.com/t/YFI:USD",
            "price": 24117.0,
            "last_update": "2021-12-07T17:49:54.000Z",
            "exchange_id": 37
        },
        {
            "exchange_name": "Binance",
            "market_url": "https://www.binance.com/en/trade/YFI_BUSD",
            "price": 24061.58763433993,
            "last_update": "2021-12-07T17:49:54.000Z",
            "exchange_id": 270
        },
        {
            "exchange_name": "Coinbase Exchange",
            "market_url": "https://pro.coinbase.com/trade/YFI-BTC",
            "price": 24020.347144833217,
            "last_update": "2021-12-07T17:48:57.000Z",
            "exchange_id": 89
        },
        {
            "exchange_name": "FTX US",
            "market_url": "https://ftx.us/trade/YFI/USD",
            "price": 23985.0,
            "last_update": "2021-12-07T17:48:07.000Z",
            "exchange_id": 1177
        },
        {
            "exchange_name": "Binance",
            "market_url": "https://www.binance.com/en/trade/YFI_EUR",
            "price": 24018.992856877743,
            "last_update": "2021-12-07T17:49:54.000Z",
            "exchange_id": 270
        },
        {
            "exchange_name": "Bitfinex",
            "market_url": "https://www.bitfinex.com/t/YFI:UST",
            "price": 24036.37648809482,
            "last_update": "2021-12-07T17:49:54.000Z",
            "exchange_id": 37
        }
     }
]

【问题讨论】:

  • 使用一个简单的 if 条件来检查它是否是一个有效的 exchangeid,同时遍历你的 JSON 对象?
  • 您应该发布 input JSON 数据而不是您当前的 output JSON 数据以重现问题。理想情况下,将您的示例代码设置为 minimal reproducible exampleread 以输入数据并对其进行处理,而不是发布无效代码。

标签: python json


【解决方案1】:

要仅获取您想要的交易所 ID 的信息,只需在创建 pairs 列表时检查它们。由于 id 是可散列的,因此在 Python 中执行此操作的最快方法是将 id 存储在 set 中,这样可以非常快速地检查成员资格。

pairs = []
desired_ids = {102,311,200,302,521,433,482,406,42,400}  # Exchange ids

for pair in json_data["marketPairs"]:
    if pair["exchangeId"] in desired_ids:
        pairs.append({
            "exchange_name": pair["exchangeName"],
            "market_url": pair["marketUrl"],
            "price": pair["price"],
            "last_update" : pair["lastUpdated"],
            "exchange_id": pair["exchangeId"]
            })

建议

您可以简化转换过程并使其更加“数据驱动”,方法是使用字典显示(或更常用的 dictionary comprehension)来创建带有重命名键并附加到 pairs 的键列表。

pairs = []
desired_ids = {102,311,200,302,521,433,482,406,42,400}  # Exchange ids
oldkeys = 'exchangeName', 'marketUrl', 'price', 'lastUpdated', 'exchangeId'
newkeys = 'exchange_name', 'market_url', 'price', 'last_update', 'exchange_id'

for pair in json_data["marketPairs"]:
    if pair["exchangeId"] in desired_ids:
        pairs.append({newkey: pair[oldkey] for oldkey, newkey in zip(oldkeys, newkeys)})

【讨论】:

    【解决方案2】:
    exchanges = [102,311,200,302,521,433,482,406,42,400]
    
    for pair in json_data["marketPairs"]:
        #Condition like Ronald Das Mentioned 
        if pair["exchangeId"] in exchanges:
                pairs.append({
                    "exchange_name": pair["exchangeName"],
                    "market_url": pair["marketUrl"],
                    "price": pair["price"],
                    "last_update" : pair["lastUpdated"],
                    "exchange_id": pair["exchangeId"] #That ids what I'm would to have 102,311,200,302,521,433,482,406,42,400
                                    
                 })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2014-08-27
      • 2016-03-11
      • 2013-01-01
      相关资源
      最近更新 更多