所以我正在从一个网站上读取一个json,这是我输出的一部分
{"objects": [{"first_name": "Pascale", "last_name": "D\u00e9ry",...
在四处搜索时,我发现\u00e9是一个与é相对应的unicode字符。好吧,我明白了。但是,当我试图解决这个问题时,我认为我应该在从网站读取数据时使用.encode(),如下所示:
^{pr2}$但后来我发现了错误
AttributeError: 'bytes' object has no attribute 'encode'
我是不是把事情弄反了?我也试过了。解码('utf-8'),但也没用。(Get-TypeError:“str”不支持缓冲区接口)
我应该提到我使用的是python3。在
如果您的真正目标是将数据存储在电子表格中,请尝试以下程序:
注意:这个程序需要Python3。如果你用的是Python2,告诉我,我会给你一个在那里工作的版本。在
在本例中,
decode()
将是对下载的JSON字符串执行的适当操作。在考虑这个简化的示例,它将通过在URL中指定
limit=1&offset=0
来下载单个候选对象的JSON:由此我们可以看到内容的类型是bytes,即字节字符串。字节字符串没有
encode()
方法;它们被假定已经在某些编码中,并且只能使用正确的编码将其解码为unicode。在本例中,数据是UTF-8编码的JSON,如Content-Type
报头所示。在你可以在这里做很多事情:
以二进制模式打开输出文件,只需编写JSON字符串 和文件一样。因为传入的数据是UTF-8编码的 将生成一个UTF-8编码的JSON文件,这可能是 CSV转换器要求:
^{2美元使用支持的编码以文本模式打开输出文件 CSV转换器,将来自UTF-8的传入JSON字符串解码为文本 字符串(unicode),并将解码后的字符串写入文件:
这里我选择了iso-8859-1编码作为例子,你也可以选择ASCII。请注意,如果编码是UTF-8,那么将对数据进行解码,然后将其重新编码为UTF-8,所以您可以像第一次一样编写数据。
另一个选项,也是我推荐的一个,是使用JSON解码器对传入的数据进行解码,然后使用您首选的编码将其写入文件。这样做的好处是确保传入的数据实际上是JSON,并允许您在传递给CSV转换器之前发现任何错误:
您可能会发现使用^{} 模块更容易。内置JSON解析和字符解码:
这里
r.content
是下载的原始内容,无论服务器发送数据的编码是什么。r.text
相同的原始内容被解码成unicode字符串。并且r.json()
将解析后的JSON数据作为字典提供给您。然后,将其写入文件非常简单:相关问题 更多 >
编程相关推荐