首页 > 解决方案 > 如何从python中的http响应解析json?

问题描述

我的本地主机中有一个 API。当我在浏览器上调用它时,我会看到以下信息:

<string xmlns="http://tempuri.org/">
{"STATUS":"202","STATUS_DT":"98/12/07","CitizenMobile":"091234567","PROFILEKEY":"1233"}
</string>

我想在我的代码中使用这些信息,并将parse其作为json. 我的代码是:

import json
import requests

url = ""
response = requests.get(url)

print("type of response= ",type(response))
print(response.status_code)

data = response.text
parsed = json.loads(data)

print(parsed)

我的输出是:

type of response=  <class 'requests.models.Response'>
200

Traceback (most recent call last):
  File "C:/Users/MN/dev/New Project/form/WebService/TEST_MAZAHERI/Test_Stack.py", line 11, in 
 <module>
parsed = json.loads(data)
File "C:\Users\MN\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\MN\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\MN\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 355, in 
raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我遇到了这个错误:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 你能帮帮我吗?

标签: jsonpython-3.xpython-requests

解决方案


只需使用 response.json 获取 json 格式的数据

import json
import requests

url = ""
response = requests.get(url)

print("type of response= ",type(response))
print(response.status_code)

data = response.json # changed here

print(data)

推荐阅读