【问题标题】:How to parse json from http response in python?如何从python中的http响应解析json?
【发布时间】:2020-02-25 06:32:11
【问题描述】:

我的本​​地主机中有一个 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) 你能帮帮我吗?

【问题讨论】:

    标签: json python-3.x python-requests


    【解决方案1】:

    只需使用 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)
    

    【讨论】:

      【解决方案2】:

      试试这个。工作正常。 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.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-27
        • 1970-01-01
        • 2019-12-11
        相关资源
        最近更新 更多