Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Key error while getting header from json load

Here is the piece of code I wrote to output json data from api link

import requests
import json
from urllib.request import Request, urlopen

req = Request('https://servers-frontend.fivem.net/api/servers/single/4lqxao'), headers={'User-Agent': 'Mozilla/5.0'})
sopen = urlopen(req, timeout=10)
data = json.loads(sopen.read())
print(data["clients"])

but when I try to print specified header value I get this error (json output prints correctly, but specified header doesn’t)

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is a problem?

>Solution :

First of all you have a typo in the code you provided, I believe you mean

req = Request('https://servers-frontend.fivem.net/api/servers/single/4lqxao', headers={'User-Agent': 'Mozilla/5.0'})

instead of

req = Request('https://servers-frontend.fivem.net/api/servers/single/4lqxao'), headers={'User-Agent': 'Mozilla/5.0'})

Secondly, the response comprises of a dictionary of two keys, ‘Endpoint’ and ‘Data’ and the ‘client’ key you are looking for exists in the nested ‘Data’ dictionary. As a result you can access it through data[‘Data’][‘clients’]. Verified it myself.

print(data['Data']['clients'])

140

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading