![](/img/trans.png)
[英]How to parse only 1 variable from JSON HTTP response Spring Boot
[英]How to parse json from http response in python?
我的本地主机中有一个 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)
你能帮我吗?
只需使用 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)
尝试这个。 工作正常。 JSON 在 XML 中,获取数据,将其作为string
放入 xml 库并从标签中获取 json。
>>> data = r'<string xmlns="http://tempuri.org/"> {"STATUS":"202","STATUS_DT":"98/12/07","CitizenMobile":"091234567","PROFILEKEY":"1233"}</string>'
>>> from io import StringIO
>>> from lxml import etree
>>> root = etree.parse(StringIO(data))
>>> r = root.getroot()
>>> r.tag #also, you can iterate through particular tag, if xml has multiple tags
'{http://tempuri.org/}string'
>>> r.text #Get json text
' {"STATUS":"202","STATUS_DT":"98/12/07","CitizenMobile":"091234567","PROFILEKEY":"1233"}'
>>>
>>> import json
>>> json.loads(r.text)
{'STATUS': '202', 'STATUS_DT': '98/12/07', 'CitizenMobile': '091234567', 'PROFILEKEY': '1233'}
>>> #further operations add here.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.