Как мне более эффективно проанализировать эти json данные с помощью Python? - PullRequest
0 голосов
/ 03 апреля 2020

Как мне проанализировать эти json данные более эффективным способом. Я хотел бы сделать это с помощью для l oop, чтобы код не повторялся.

Вот конечная точка данных: 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>

Мне удалось проанализировать другие json данные, используя forl oop, но структура была другой. ниже приведен список таких словарей:

[
  {
    "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>

Это сработало хорошо.

спасибо

1 Ответ

0 голосов
/ 03 апреля 2020

@ Комментарий ThierryLathuille был правильным и решил проблему.

Затем в шаблоне html я смог получить доступ к данным с помощью для l oop:

<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>
...