解析值包含“&”的查询字符串

parse query string where value has "&"

我正在处理第三方套接字 API,我在其中获取字符串响应并将其转换为 JSON。

示例:

id=1000&name=Foo Bar

我已尝试 split('&')parse_qsl 以获得结果(作为键、值)。问题是对于某些记录,该值包含 &

例子

id=1000&name=Foo Bar & Bros

所以 & Bros 将被视为空值。知道如何将其解析为名称键的一部分吗?

有意思。问题是具有 "Foo Bar & Bros" 值的字符串不是有效的查询字符串; spaces 和(文本)符号需要进行编码。

但是,假设 1) 您提到的 "third party socket API" 以这种损坏的形式提供给您,并且 2) 文本和符号周围总是有一个 space,您可以做到像这样:

def handle_ampersand_values(pseudo_querystring):
    ENCODED_TEXTUAL_AMPERSAND = " AMPERSAND "
    RAW_TEXTUAL_AMPERSAND = " & "
    encoded_ampersands = pseudo_querystring.replace(RAW_TEXTUAL_AMPERSAND, ENCODED_TEXTUAL_AMPERSAND)
    kv_segments = encoded_ampersands.split("&")
    kv_pairs = [segment.split("=") for segment in kv_segments]
    return {k: v.replace(ENCODED_TEXTUAL_AMPERSAND, RAW_TEXTUAL_AMPERSAND) for k, v in kv_pairs}

print(handle_ampersand_values("id=1000&name=Foo Bar & Bros"))
{'id': '1000', 'name': 'Foo Bar & Bros'}