Kalakutas
Kalakutas

Reputation: 134

python Issue with getting correct info from the json

I have issue then i try get from correct information. For example i have very big json output after request i made in post (i cant use get).

 "offers": [
    {
        "rank": 1,
        "provider": {
            "id": 6653,
            "isLocalProvider": false,
            "logoUrl": "https://img.vxcdn.com/i/partner-energy/c_6653.png?v=878adaf9ed",
            "userRatings": {
                "additonalCustomerRatings": {
                    "price": {
                        "percent": 73.80
                    },
                    "service": {
                        "percent": 67.50
                    },
                    "switching": {
                        "percent": 76.37
                    },
                    "caption": {
                        "text": "Zusätzliche Kundenbewertungen"
                    }
                },

I cant show it all because its very big. Like you see "rank" 1 in this request exist 20 ranks with information like content , totalCost and i need pick them all. Like 6 rank content and totalCost, 8 rank content and totalCost.

So first off all in python i use code for getting what json data.

import requests
import json


url = "https://www.verivox.de/api/energy/offers/electricity/postCode/10555/custom?"

payload="{\"profile\":\"H0\",\"prepayment\":true,\"signupOnly\":true,\"includePackageTariffs\":true,\"includeTariffsWithDeposit\":true,\"includeNonCompliantTariffs\":true,\"bonusIncluded\":\"non-compliant\",\"maxResultsPerPage\":20,\"onlyProductsWithGoodCustomerRating\":false,\"benchmarkTariffId\":741122,\"benchmarkPermanentTariffId\":38,\"paolaLocationId\":\"71085\",\"includeEcoTariffs\":{\"includesNonEcoTariffs\":true},\"maxContractDuration\":240,\"maxContractProlongation\":240,\"usage\":{\"annualTotal\":3500,\"offPeakUsage\":0},\"priceGuarantee\":{\"minDurationInMonths\":0},\"maxTariffsPerProvider\":999,\"cancellationPeriod\":null,\"previewDisplayTime\":null,\"onlyRegionalTariffs\":false,\"sorting\":{\"criterion\":\"TotalCosts\",\"direction\":\"Ascending\"},\"includeSpecialBonusesInCalculation\":\"None\",\"totalCostViewMode\":1,\"ecoProductType\":0}"
headers = {
  'Content-Type': 'application/json',
  'Cookie': '__cfduid=d97a159bb287de284487ebdfa0fd097b41606303469; ASP.NET_SessionId=jfg3y20s31hclqywloocjamz; 0e3a873fd211409ead79e21fffd2d021=product=Power&ReturnToCalcLink=/power/&CustomErrorsEnabled=False&IsSignupWhiteLabelled=False; __RequestVerificationToken=vrxksNqu8CiEk9yV-_QHiinfCqmzyATcGg18dAqYXqR0L8HZNlvoHZSZienIAVQ60cB40aqfQOXFL9bsvJu7cFOcS2s1'
}

response = requests.request("POST", url, headers=headers, data=payload)

jsondata = response.json()

# print(response.text)

For it working fine, but then i try pick some data what i needed like i say before im getting

    for Rankdata in str(jsondata['rank']):
KeyError: 'rank'

my code for this error.

dataRank = []

for Rankdata in str(jsondata['rank']):
   dataRank.append({
     'tariff':Rankdata['content'],
     'cost': Rankdata['totalCost'],
     'sumOfOneTimeBonuses': Rankdata['content'],
     'savings': Rankdata['content']
     })

Then i try do another way. Just get one or some data, but not working too.

data = response.json()
#print(data)
test = float((data['rank']['totalCost']['content']))

I know my code not perfect, but i first time deal with json what are so big and are so difficult. I will be very grateful if show my in my case example how i can pick rank 1 - rank 20 data and print it.

Thank you for your help.

Upvotes: 0

Views: 70

Answers (1)

fabero
fabero

Reputation: 85

If you look closely at the highest level in the json, you can see that the value for key offers is a list of dicts. You can therefore loop through it like this:

for offer in jsondata['offers']:
  print(offer.get('rank'))
  print(offer.get('provider').get('id'))

And the same goes for other keys in the offers.

Upvotes: 1

Related Questions