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)
What is a problem?
CodePudding user response:
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