当我在Postman中发出这个POST请求时,我得到了数据。当我在Python 2.7(使用Jupyter笔记本)中执行此操作时,我收到错误“无法解码JSON对象”。我做错了什么,我怎么能让它运作起来?
import json
import requests
url = 'http://api.scb.se/OV0104/v1/doris/en/ssd/BE/BE0101/BE0101A/BefolkningNy'
headers={'content-type': 'application/json'}
payload = {
"query": [
{
"code": "ContentsCode",
"selection": {
"filter": "item",
"values": [
"BE0101N1"
]
}
},
{
"code": "Tid",
"selection": {
"filter": "item",
"values": [
"2010",
"2011"
]
}
},
{
"code": "Region",
"selection": {
"filter": "item",
"values": [
"01"
]
}
}
],
"response": {
"format": "json"
}
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=payload)
print(r.text)
print(r.json())
api的手册在这里,但没有多大帮助:
http://www.scb.se/en_/About-us/Open-data-API/API-for-the-Statistical-Database-/
答案 0 :(得分:5)
设置json=payload
,请求将添加您需要的标头:
url = 'http://api.scb.se/OV0104/v1/doris/en/ssd/BE/BE0101/BE0101A/BefolkningNy'
payload = ....
r = requests.post(url, json=payload)
那会给你你的json:
In [7]:
...: r = requests.post(url, json=payload)
...: print(r.json())
...:
{u'data': [{u'values': [u'2054343'], u'key': [u'01', u'2010']}, {u'values': [u'2091473'], u'key': [u'01', u'2011']}], u'comments': [], u'columns': [{u'text': u'region', u'code': u'Region', u'type': u'd'}, {u'text': u'year', u'code': u'Tid', u'type': u't'}, {u'text': u'Population', u'code': u'BE0101N1', u'type': u'c'}]}
如果碰巧遇到 json.decoder.JSONDecodeError:意外的UTF-8 BOM(使用utf-8-sig解码):错误将编码设置为 utf-8-sig :
r = requests.post(url, json=payload)
r.encoding = "utf-8-sig"
print(r.json())