POST 请求在 Postman 中有效,但在 Python 中无效

2023-11-26

当我在 Postman 中发出此 POST 请求时,我会获取数据。当我在 Python 2.7 中(使用 Jupyter Notebook)执行此操作时,出现错误“无法解码任何 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-/


Set 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())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

POST 请求在 Postman 中有效,但在 Python 中无效 的相关文章

随机推荐