简体   繁体   中英

How to read a JSON result in Python3

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

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM