簡體   English   中英

用python讀取json字符串的問題

[英]issue reading json string with python

我正在嘗試使用Python讀取Twitter流。

我文件中的行似乎正確,如下所示:

{"delete":{"status":{"id":471622360253345792,"user_id":2513833684,"id_str":"471622360253345792","user_id_str":"2513833684"}}}

當我使用readline將這行讀入內存並對其調用json.loads()時,出現以下錯誤:

No JSON object could be decoded

我想我必須在調用json.loads()之前以某種方式轉換行?

一些注意事項:

  1. 如果我將文件中的字符串粘貼到IPython中並在其上調用json.loads(),則一切正常。
  2. 當我在IPython中打印行時,它在前面添加了一個奇怪的字符,並在其余字符之間放置了空格。 前幾個字符如下所示:

    {“刪除”:{“狀態

  3. 如果我在IPython中顯示字符串而不調用print,則前幾個字符為:

    \\ xff \\ xfe {\\ x00“ \\ x00d \\ x00e \\ x00l \\ x00e \\ x00t \\ x00e \\ x00” \\ x00:\\ x00 {\\ x00“ \\ x00s \\ x00t \\ x00a \\ x00t \\ x00u \\ x00s \\ x00s \\ x00” \\ x00

我不知道該如何解決。

編輯:根據要求,讀取twitter流的代碼在這里:

https://github.com/uwescience/datasci_course_materials/blob/master/assignment1/twitterstream.py

從外觀上看,您有一些非ASCII文本,並且解析器可能未處理不同的編碼。

如果查看json庫上的文檔,則會看到:

If the contents of fp are encoded with an ASCII based encoding other than UTF-8 
(e.g. latin-1), then an appropriate encoding name must be specified. Encodings 
that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped 
with codecs.getreader(encoding)(fp), or simply decoded to a unicode object and 
passed to loads().

因此,我將檢查您的json格式是否正確,然后查看編碼。

json.loads(twitter_data, encoding='utf-16')

您是否使用Windows進行作業? 在Windows下檢索到的文本文件的默認編碼為UCS-2 LE BOMjson.loads()無法識別。 您既可以使用Linux OS,也可以使用諸如Notepad ++之類的第三方軟件,在其中可以方便地保存為UTF-8編碼。

暫無
暫無

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

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