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

时间:2018-01-27 01:46:10

标签: python json python-3.x character-encoding

我在这里丢弃。我正在尝试将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"])

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

更新

该字符串的作用是json.loads(str(data.encode('unicode_escape'), 'utf-8'))但是,它不适用于较大的字符串。我在更大的json字符串

上执行此操作的错误是JSONDecodeError: Invalid \escape

3 个答案:

答案 0 :(得分:3)

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

完成的转义值

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

这可以通过对latin-1编码所期望的内容进行编码,同时将任何\u003类似的转义字符解释为字面\u003,除非它是某种控制字符。

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

在将编码后的字符串转换回普通的python字符串后,注意控件字符会消失,可以看到这一点:

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

如果你想保留控制字符,你必须在加载之前尝试转义字符串。

答案 1 :(得分:2)

如果您使用的是Python 3.6或更高版本,我认为您可以使用

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

根据docs,这会给你一个

  

适合作为Unicode文字内容的编码   ASCII编码的Python源代码,但报价不会被转义。   从Latin-1源代码解码。请注意Python源代码   实际上默认使用UTF-8。

这似乎正是你所需要的。

答案 2 :(得分:0)

确定。因为我在Windows上,我必须设置控制台来处理特殊字符。我通过在终端中键入chcp 65001来完成此操作。我还使用正则表达式并链接字符串操作函数,无论如何都是python方式。

usable_json = json.loads(re.search('start_sub_string(.*)end_sub_string', hxs.xpath("//script[contains(., 'some_string')]//text()").extract_first()).group(1))

然后一切都变得平静了。在写入数据库时​​,我将对编码和转义进行整理。

相关问题