繁体   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