如何过滤 python 中的 .json 数组,以便每个元素中只显示一个参数?
How do I filter a .json array in python so that only one parameter in each element shows?
正如标题所说,我在过滤从 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']
你的列表理解有点在那里,但你应该在每个字典中建立索引而不是使用 if
子句。它应该看起来像:
[item["id"] for item in jsonCall]
这输出:
['01coin', '0-5x-long-algorand-token', '0-5x-long-altcoin-index-token']
正如标题所说,我在过滤从 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']
你的列表理解有点在那里,但你应该在每个字典中建立索引而不是使用 if
子句。它应该看起来像:
[item["id"] for item in jsonCall]
这输出:
['01coin', '0-5x-long-algorand-token', '0-5x-long-altcoin-index-token']