使用python读取json字符串时出现问题

2024-06-16 19:36:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python阅读twitter流。在

我的文件中的行看起来是正确的,如下所示:

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

当我用readline和call将这行读入内存时json.loads()在它上面,我得到以下错误:

^{pr2}$

我想在打电话之前我得把线路改一下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

我不知道怎么解决这个问题。在

编辑:根据请求,读取twitter流的代码如下:

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


Tags: 文件字符串idjsonipythontwitter字符x00
3条回答
json.loads(twitter_data, encoding='utf-16')

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

你在用窗户做作业吗?在Windows下检索到的文本文件的默认编码是UCS-2 LE BOM,它不能被json.loads()识别。您可以使用Linux操作系统,也可以使用第三方软件,如Notepad++,您可以方便地将其保存为UTF-8编码。在

相关问题 更多 >