三行代码  ›  专栏  ›  技术社区  ›  TheCryptoChad

如何过滤a。python中的json数组,以便每个元素中只显示一个参数?

  •  1
  • TheCryptoChad  · 技术社区  · 1 月前

    正如标题所说,我在过滤从CoinGecko API获取的数组时遇到问题。阵列如下所示:

    [
      {
        "id": "01coin",
        "symbol": "zoc",
        "name": "01coin"
      },
      {
        "id": "0-5x-long-algorand-token",
        "symbol": "algohalf",
        "name": "0.5X Long Algorand Token"
      },
      {
        "id": "0-5x-long-altcoin-index-token",
        "symbol": "althalf",
        "name": "0.5X Long Altcoin Index Token"
      }
    ]
    

    在过滤器之后,我希望它只显示“id”,如下所示:

    [
      "01coin",
      "0-5x-long-algorand-token",
      "0-5x-long-altcoin-index-token"
    ]
    

    以下是我试图过滤它的方式:

    coinList = 'https://api.coingecko.com/api/v3/coins/list'
    listCall = requests.get(coinList)
    jsonCall = json.loads(listCall.content)
    coinIds = [x for x in jsonCall if x == 'id']
    
    1 回复  |  直到 1 月前
        1
  •  4
  •   BrokenBenchmark    1 月前

    您的列表理解在某种程度上是这样的,但您应该在每个词典中建立索引,而不是使用 if 条款它应该看起来像:

    [item["id"] for item in jsonCall]
    

    这将输出:

    ['01coin', '0-5x-long-algorand-token', '0-5x-long-altcoin-index-token']