对原始字符串进行编码,以便将其解码为 json

Den*_*itt 2 python json character-encoding python-3.x

我在这里认输。我正在尝试将从带有scrapy(注入javascript)的网站源代码中抓取的字符串转换为json,以便我可以轻松访问数据。问题归结为解码错误。我尝试了各种编码、解码、转义、编解码器、正则表达式、字符串操作,但没有任何效果。哦,使用 Python 3。

我缩小了字符串(或至少部分)上的罪魁祸首

scraped = '{"propertyNotes": [{"title": "Local Description", "text": "\u003Cp\u003EAPPS\u003C/p\u003E\n\n\u003Cp\u003EBig Island Revealed (comes as app or as a printed book)\u003C/p\u003E\n\n\u003Cp\u003EAloha Big Island\u003C/p\u003E\n\n\u003Cp\u003EBig Island\u003C/p\u003E\n\n\u003Cp\u003EBig Island Smart Maps (I like this one a lot)\u003C/p\u003E\n\n\u003Cp\u003EBig Island Adventures (includes videos)\u003C/p\u003E\n\n\u003Cp\u003EThe descriptions of beaches are helpful.  Suitability for swimming, ease of access, etc. is included.  Some beaches are great for picnics and scenic views, while others are suitable for swimming and snorkeling. Check before you go.\u003C/p\u003E"}]}'

scraped_raw = r'{"propertyNotes": [{"title": "Local Description", "text": "\u003Cp\u003EAPPS\u003C/p\u003E\n\n\u003Cp\u003EBig Island Revealed (comes as app or as a printed book)\u003C/p\u003E\n\n\u003Cp\u003EAloha Big Island\u003C/p\u003E\n\n\u003Cp\u003EBig Island\u003C/p\u003E\n\n\u003Cp\u003EBig Island Smart Maps (I like this one a lot)\u003C/p\u003E\n\n\u003Cp\u003EBig Island Adventures (includes videos)\u003C/p\u003E\n\n\u003Cp\u003EThe descriptions of beaches are helpful.  Suitability for swimming, ease of access, etc. is included.  Some beaches are great for picnics and scenic views, while others are suitable for swimming and snorkeling. Check before you go.\u003C/p\u003E"}]}'

data = json.loads(scraped_raw) #<= works
print(data["propertyNotes"])

failed = json.loads(scraped) #no work
print(failed["propertyNotes"])
Run Code Online (Sandbox Code Playgroud)

不幸的是,我找不到scrapy/splash 将字符串返回为原始字符串的方法。所以,不知何故,我需要让python在加载json时将字符串解释为原始字符串。请帮忙

更新:

对那个字符串起作用的是json.loads(str(data.encode('unicode_escape'), 'utf-8'))但是,它不适用于较大的字符串。我这样做的错误是JSONDecodeError: Invalid \escape在较大的 json 字符串上

小智 5

问题存在是因为你得到的字符串已经转义了控制字符,当被 python 解释时,这些字符在编码时变成了实际的字节(虽然这不一定是坏的,我们知道这些转义字符是 json 不期望的控制字符)。与 Turn 的答案类似,您需要解释字符串而不解释使用完成的转义值

json.loads(scraped.encode('unicode_escape'))

这通过按 latin-1 编码的预期对内容进行编码来工作,同时将任何\u003类似的转义字符解释为字面意思,\u003除非它是某种控制字符。

但是,如果我的理解是正确的,您可能不希望这样,因为您会丢失转义的控制字符,因此数据可能与原始数据不同。

您可以通过注意到在将编码字符串转换回普通 python 字符串后控制字符消失来看到这一点:

scraped.encode('unicode_escape').decode('utf-8')

如果要保留控制字符,则必须在加载字符串之前尝试对其进行转义。