有一个web服务返回类似的内容,我想在此响应中访问id。我该怎么办?
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{"id":"1819","responseCode":"0","responseMessage":"0"}</string>
另外,我的功能在这里:
import requests
def sen_request():
url = "somewhere.com/somewhere.asmx/new_one"
payload = {}
headers= {}
response = requests.request("GET", url, headers=headers, data = payload)
return (response)
- 我试图用response.JSON((访问JSON中的响应,但符合此错误:
Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0)
代码使用json-lib和XML-lib解析来提取id
import json
import xml.etree.ElementTree as ET
data = '''<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{"id":"1819","responseCode":"0","responseMessage":"0"}</string>'''
data1 = '''<?xml version="1.0" encoding="utf-8"?><string xmlns="tempuri.org">{"id":{"id1":"1819"},"responseCode":"0","responseMessage":"0"}</string>'''
root = ET.fromstring(data)
print(json.loads(root.text)['id'])
root = ET.fromstring(data1)
print(json.loads(root.text)['id']['id1'])
输出
1819
1819