Skip to main content
 首页 » 编程设计

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

2025年05月04日21开发

我在这里认输了。我正在尝试将从带有 scrapy(注入(inject)的 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"]) 

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

更新:

适用于该字符串的是 json.loads(str(data.encode('unicode_escape'), 'utf-8')) 但是,它不适用于较大的字符串。我这样做的错误是 JSONDecodeError: Invalid\escape on the larger json string

请您参考如下方法:

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

完成的转义值

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

这通过按 latin-1 编码预期的方式对内容进行编码,同时将任何 \u003 之类的转义字符解释为字面上的 \u003 除非它是某种控制字符.

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

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

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

如果你想保留控制字符,你将不得不在加载它们之前尝试转义字符串。