【问题标题】:issue reading json string with python用python读取json字符串的问题
【发布时间】:2014-07-02 22:26:26
【问题描述】:

我正在尝试使用 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 中打印该行时,它会在前面添加一个奇怪的字符,并在其余字符之间放置空格。前几个字符看起来像:

    �{"d e l e t e" : {" s t a t u s

  3. 如果我在 IPython 中显示字符串而不调用 print,前几个字符是:

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

我不知道如何解决这个问题。

编辑:根据要求,读取推特流的代码在这里:

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

【问题讨论】:

标签: python json twitter


【解决方案1】:

从外观上看,您有一些非 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 格式是否正确,然后查看编码。

【讨论】:

    【解决方案2】:
    json.loads(twitter_data, encoding='utf-16')
    

    【讨论】:

      【解决方案3】:

      您是否使用 Windows 进行作业? Windows下检索到的文本文件默认编码为UCS-2 LE BOMjson.loads()无法识别。您可以使用 Linux 操作系统,也可以使用 Notepad++ 等第三方软件,在其中可以方便地保存为UTF-8 编码。

      【讨论】:

        猜你喜欢
        • 2010-11-12
        • 1970-01-01
        • 2012-04-06
        • 1970-01-01
        • 2020-05-17
        • 1970-01-01
        • 2018-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多