I try to read JSON-formatted data from the following public URL: http://ws-old.parlament.ch/factions?format=json. Unfortunately, I was not able to convert the response to JSON as I always get the HTML-formatted content back from my request. Somehow the request seems to completely ignore the parameters for JSON formatting passed with the URL:
JavaScript
x
5
1
import urllib.request
2
response = urllib.request.urlopen('http://ws-old.parlament.ch/factions?format=json')
3
response_text = response.read()
4
print(response_text) #why is this HTML?
5
Does somebody know how I am able to get the JSON formatted content as displayed in the web browser?
Advertisement
Answer
You need to add "Accept": "text/json"
to request header.
For example using requests package:
JavaScript
1
4
1
r = requests.get(r'http://ws-old.parlament.ch/factions?format=json',
2
headers={'Accept':'text/json'})
3
print(r.json())
4
Result:
JavaScript
1
2
1
[{'id': 3, 'updated': '2022-02-22T14:59:17Z', 'abbreviation':
2