Home > OS >  Extracting JSON value from its parent
Extracting JSON value from its parent

Time:06-21

I am making a request and I want to parse its response:

{"hash160":"4b1ddbf92df072c298a0c58043db58b26771f926","address":"17rBT3f4UmnFGrngasBprqXjQQnZVztfDz","n_tx":0,"n_unredeemed":0,"total_received":0,"total_sent":0,"final_balance":0,"txs":[]}

I tried to extract values total_sent and final_balance like this: print(str(wallet['n_tx']['total_sent'])) and I got a Type Error: 'int' object is not subscriptable

How can I extract those values?

CodePudding user response:

If you just want to print them both out you can try this:

[print(str(wallet[i])) for i in ['n_tx', 'total_sent']]

The reason you are getting the error is because wallet['n_tx'] is an integer and therefore has no total_sent key. In order to access both values you need to extract them one at a time.

a = wallet['n_tx']
b = wallet['total_sent']

CodePudding user response:

The code you are including is essentially asking for value indexed by 'total_sent' WITHIN wallet['n_tx'].

If you want 'n_tx' and 'total_sent',

n_tx = wallet['n_tx']
total_sent = wallet['total_sent']
print(n_tx, total_sent)
  • Related