簡體   English   中英

使用python解析HTTP數組響應

[英]Parsing HTTP array response with python

我正在嘗試通過json解析HTTP響應,但它給了我字符錯誤,但是當我嘗試通過for循環遍歷此響應時,它將所有內容拆分為單個字符。 有沒有更好的方法來解析此響應?

碼:

    _url = self.MAIN_URL
    try:
        _request = self.__webSession.get(_url, cookies=self.__cookies)
        if _request.status_code != 200:
            self.log("Request failed with code: {}. URL: {}".format(_request.status_code, _url))
            return
    except Exception as err:
        self.log("[e4] Web-request error: {}. URL: {}".format(err, _url))
        return

    _text = _request.json()

json.loads()返回以下內容

 Expecting value: line 1 column 110 (char 109)

HTTP響應需要解析:

[
  [
    9266939,
    'Value1',
    'Value2',
    'Value3',
            ,
    'Value4',
        [
            [
                'number',
                'number2',
                    [
                        'value',
                               ,
                        'value2'
                    ]
            ]
        ]
  ],
  [
    5987798,
    'Value1',
    'Value2',
            ,
    'Value3',
    'Value4',
        [
            [
                'number',
                'number2',
                    [
                        'value',
                        'value2'
                    ]
            ]
        ]
  ]
]

盡管由於行號和列號而使錯誤消息令人困惑,但是JSON格式在任何情況下都不接受字符串的單引號,因此給定的HTTP響應不是JSON格式。 您必須對字符串使用雙引號。

因此,您必須改為這樣輸入(如果您可以控制它):

[
  [
    9266939,
    "Value1",
    "Value2",
    "Value3",
    "Value4",
    [
        [
        "number",
        "number2",
            [
            "value",
            "value2"
            ]
        ]
...

如果您無法控制要解析的HTTP響應,則可以在解析之前將所有單引號替換為雙引號:

http_response_string = (get the HTTP response)
adjusted_http_response_string = http_response_string.replace("'", '"')
data = json.loads(adjusted_http_response_string)

但這當然帶有替換單引號(或單引號)的潛在風險,這些單引號不是字符串分隔符。 但是,它在大多數時間都可以充分解決問題。

編輯:

根據注釋中的要求進一步清理:

http_response_string = (get the HTTP response)

# More advanced replacement of ' with ", expecting
# strings to always come after at least four spaces,
# and always end in either comma, colon, or newline.
adjusted_http_response_string = \
    re.sub("(    )'", r'\1"',
    re.sub("'([,:\n])", r'"\1',
    http_response_string))

# Replacing faulty ",  ," with ",".
adjusted_http_response_string = \
    re.sub(",(\s*,)*", ",", 
    adjusted_http_response_string)

data = json.loads(adjusted_http_response_string)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM