Karan
Karan

Reputation: 498

Fetch Keys from Response Dictionary

Sending Client request to get data from API.

request =client.get_income('ET',incomeType='PNL',startTime=1611287550000) 

The API returns the following data:

[{"symbol":"ET","incomeType":"R","income":"-2.4","time":1611287909000,"info":"50538270"},{"symbol":"ET","incomeType":"R","income":"1.68","time":1611287909000,"info":"50538271"}]

It's a dictionary inside the list. When I try to access the items through a for loop or any of the following methods, It returns the OBJECT.

Methods I tried:

for item in request:
    print(item['income'])

returns this : <model.income.Income object at 0x000000684EFB4580>
print(request[0]['income']
ERROR: TypeError: 'Income' object is not subscriptable

None of them works.

Upvotes: 1

Views: 232

Answers (3)

Karan
Karan

Reputation: 498

I have fixed it myself.

request =client.get_income('ET',incomeType='PNL',startTime=1611287550000)

for x in range(len(request)):
    print(request[x].__dict__['income'])

Upvotes: 1

pakpe
pakpe

Reputation: 5489

The data structure you have is a JSON. Use Pandas to parse it and access it elements:

import pandas as pd

request = [{"symbol":"ET","incomeType":"R","income":"-2.4","time":1611287909000,"info":"50538270"},
       {"symbol":"ET","incomeType":"R","income":"1.68","time":1611287909000,"info":"50538271"}]

df = pd.DataFrame(request)
print(df)
print(f'Incomes are: {df["income"].tolist()}')

Output:

enter image description here

Upvotes: 0

iwrestledthebeartwice
iwrestledthebeartwice

Reputation: 734

request = [{"symbol":"ET","incomeType":"R","income":"-2.4","time":1611287909000,"info":"50538270"},{"symbol":"ET","incomeType":"R","income":"1.68","time":1611287909000,"info":"50538271"}]

for item in request:
    print(item['income'])

it's working fine on my pc, I'm using python 3.9

-2.4
1.68

Upvotes: 0

Related Questions