I am trying to get data from API but facing an error. I need block height from this API.
import requests
import json
fetch_json_net = requests.get('https://api.minaexplorer.com/blocks?limit=1')
blk_height_net = fetch_json_net.json()["blocks"]["blockHeight"]
print(blk_height_net)
CodePudding user response:
Here is the JSON data. You're attempting to get listed in a dictionary. It will not work if you attempt the slicing approach to get data from list. To obtain data from a dictionary, use the get method with key. Here's the code for obtaining data for "blockHeight" for the first Element.
Method One:
import requests
import json
fetch_json_net = requests.get('https://api.minaexplorer.com/blocks?limit=1')
blk_height_net = fetch_json_net.json()["blocks"][0]["blockHeight"]
print(blk_height_net)
115919
Another Method:
import requests
import json
fetch_json_net = requests.get('https://api.minaexplorer.com/blocks?limit=1')
blk_height_net = fetch_json_net.json().get("blocks")[0].get('blockHeight')
print(blk_height_net)
115919
CodePudding user response:
First of all, I checked what fetch_json_net.json()
returns:
{'blocks': [{'blockHeight': 115919, 'canonical': True, ...
It means blk_height_net["blocks"]
has a list value, not a dictionary value.
Therefore, you can get the blockHeight
value, as follows:
import requests
import json
fetch_json_net = requests.get('https://api.minaexplorer.com/blocks?limit=1')
blk_height_net = fetch_json_net.json()["blocks"][0]["blockHeight"]
print(blk_height_net)
# 115919