如何使用 Python 以更有效的方式解析此 json 数据?

How do I parse through this json data in a more efficient way with Python?

如何以更有效的方式解析此 json 数据。我想用 for 循环来做,这样代码就不会重复。

这是数据端点:https://api.coingecko.com/api/v3/exchange_rates

和json响应示例:

{
  "rates": {
    "btc": {
      "name": "Bitcoin",
      "unit": "BTC",
      "value": 1,
      "type": "crypto"
    },
    "eth": {
      "name": "Ether",
      "unit": "ETH",
      "value": 48.316,
      "type": "crypto"
    },
    "ltc": {
      "name": "Litecoin",
      "unit": "LTC",
      "value": 169.967,
      "type": "crypto"
}

我的view.py代码:

def btc_to_currency(request):

    exchange_endpoint = "https://api.coingecko.com/api/v3/exchange_rates"

    request_exchange_data = requests.get(exchange_endpoint)
    results_exchange_data = request_exchange_data.json()
    data_exchange = results_exchange_data["rates"]

    #print(data_exchange)

    btc = (data_exchange['btc'])
    xrp = (data_exchange['xrp'])
    xau = (data_exchange['xau'])
    xag = (data_exchange['xag'])


    return render(request, 'crypto/btc_to_currency.html', {'btc' : btc, 'xrp': xrp, 'xau': xau, 'xag': xag})

和我的模板 html 代码:

<table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth">
  <thead>
    <tr>
      <th rowspan="2" class="is-size-7 has-text-centered">Name</th>
      <th rowspan="2" class="is-size-7 has-text-centered">Unit</th>
      <th rowspan="2" class="is-size-7 has-text-centered">Value</th>
      <th rowspan="2" class="is-size-7 has-text-centered">Type</th>
    </tr>

  </thead>

{% load humanize %}

  <tbody>
    <tr>
      <th class="is-size-7 has-text-centered"><strong>{{ btc.name }}</strong></th>
      <td class="has-text-centered">{{ btc.unit }}</td>
      <td class="has-text-centered">{{ btc.value }}</td>
      <td class="has-text-centered">{{ btc.type }}</td>
    </tr>
    <tr>
      <th class="is-size-7 has-text-centered"><strong>{{ xrp.name }}</strong></th>
      <td class="has-text-centered">{{ xrp.unit }}</td>
      <td class="has-text-centered">{{ xrp.value|intcomma }}</td>
      <td class="has-text-centered">{{ xrp.type }}</td>
    </tr>
    <tr>
      <th class="is-size-7 has-text-centered"><strong>{{ xau.name }}</strong></th>
      <td class="has-text-centered">{{ xau.unit }}</td>
      <td class="has-text-centered">{{ xau.value }}</td>
      <td class="has-text-centered">{{ xau.type }}</td>
    </tr>
    <tr>
      <th class="is-size-7 has-text-centered"><strong>{{ xag.name }}</strong></th>
      <td class="has-text-centered">{{ xag.unit }}</td>
      <td class="has-text-centered">{{ xag.value }}</td>
      <td class="has-text-centered">{{ xag.type }}</td>
    </tr>

  </tbody>
</table>

我已经能够使用 forloop 解析其他 json 数据,但结构不同。它是如下所示的字典列表:

[
  {
    "id": "bitcoin",
    "symbol": "btc",
    "name": "Bitcoin",
    "image": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579",
    "current_price": 6915.62

  }
]

为此我使用了:

def latest(request):

    per_page_limit = int(request.GET.get('limit', 10))

    coin_list_url = f"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page={per_page_limit}&page=1&sparkline=false"

    request_coin_list = requests.get(coin_list_url)
    results_coin_list = request_coin_list.json()

    crypto_data_geckco = []

    for currency_gecko in results_coin_list:
        crypto_data_geckco.append(currency_gecko)


    return render(request, 'crypto/latest.html', { 'crypto_data_geckco': crypto_data_geckco} )

然后在模板中:

{% for currency in crypto_data_geckco %}

     <div class="box">
      <article class="media">

        <div class="media-left is-size-4">
            <figure class="image is-96x96">
                <img src="{{ currency.image }}" alt="Crypto Image Logo">
            </figure>
            <br>
            <br>
            <small><strong>{{ currency.name }} ({{ currency.symbol|upper }})</strong></small>
            <br>
            <span class="tag is-dark is-medium"><small><strong>Rank: #{{ currency.market_cap_rank }}</strong></small></span>
        </div>

{% load humanize %}
{% load mathfilters %}

        <div class="media-content">
          <div class="content media-right is-size-6">
              <br>
                <strong>{{ currency.name }} ${{ currency.current_price }}</strong>
              <br>
                <strong>Market Cap:</strong> {{ currency.market_cap|intword }}
              <br>
              <hr>
                <strong>24h Low / 24h High:</strong> ${{ currency.low_24h }} / ${{ currency.high_24h }}
              <br>
                <strong>24h Price Change:</strong> ${{ currency.price_change_24h }}
               <br>
                <strong>24h Price Change (%):</strong> {{ currency.price_change_percentage_24h|floatformat:2|intcomma }}%
               <br>
              <hr>
                <strong>Trading Volume (24hr):</strong> ${{ currency.total_volume|intword }}
              <br>
                <strong>Volume / Market Cap:</strong> {{ currency.total_volume|div:currency.market_cap|floatformat:3|intcomma }}
              <br>

效果很好。

谢谢

@ThierryLathuille 评论正确并解决了问题。

然后在 html 模板中,我能够使用 for 循环访问数据:

<table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth">
  <thead>
    <tr>
      <th rowspan="2" class="is-size-7 has-text-centered">Name</th>
      <th rowspan="2" class="is-size-7 has-text-centered">Unit</th>
      <th rowspan="2" class="is-size-7 has-text-centered">Value in BTC</th>
      <th rowspan="2" class="is-size-7 has-text-centered">Type</th>
    </tr>

  </thead>

{% for exchange in data_exchange.values %}

{% load humanize %}

  <tbody>
    <tr>
      <th class="is-size-7 has-text-centered"><strong>{{ exchange.name }}</strong></th>
      <td class="has-text-centered">{{ exchange.unit }}</td>
      <td class="has-text-centered">{{ exchange.value|intword|intcomma }}</td>
      <td class="has-text-centered">{{ exchange.type }}</td>
    </tr>

{% endfor %}

  </tbody>
</table>