0

I'm trying to calculate the exchange from US Dolar to Brazilian Reais.

I found an REST API from brazilian central bank.

My Python code is receive the API return in JSON format, like that:

{'@odata.context': 'https://was-p.bcnet.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata$metadata#_CotacaoDolarDia(cotacaoVenda)', 'value': [{'cotacaoVenda': 3.8344}]}

In my code I could isolate this part of resulte "[{'cotacaoVenda': 3.8344}]", but I can't isolate only the value "3.8344".

Follow my code:

# Cotação do Dólar V.01

import json
import requests

r = requests.get("https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/CotacaoDolarDia(dataCotacao=@dataCotacao)?@dataCotacao='03-15-2019'&$top=1&$format=json&$select=cotacaoVenda")

if r.status_code == 200:
    cotacao = json.loads(r.content)
    print(cotacao['value'])

Any idea how can I isolate only the "3.8344" contained in JSON return?

Thank you

1
  • If you are using a fairly recent version of requests, just do cotacao = r.json() Commented Mar 17, 2019 at 3:47

1 Answer 1

2

The variable cotacao, is a list, which has only one item. So we access it with index [0]. That object, is a dictionary, which we can access its fields using their key:

import json
import requests

r = requests.get("https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/CotacaoDolarDia(dataCotacao=@dataCotacao)?@dataCotacao='03-15-2019'&$top=1&$format=json&$select=cotacaoVenda")

if r.status_code == 200:
    cotacao = json.loads(r.content)
    print(cotacao['value'][0]['cotacaoVenda'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.