将json.dump移植到StringIO代码到python 3

问题描述 投票:1回答:2

我正在将Python 2应用程序移植到Python 3.当前运行Python2.7但是,更新代码以通过pylint --py3k测试,我遇到了这个问题:

def json_resource_file(baseurl, jsondata, resource_info):
    """
    Return a file object that reads out a JSON version of the supplied entity values data. 
    """
    response_file = StringIO()
    json.dump(jsondata, response_file, indent=2, separators=(',', ': '), sort_keys=True)
    response_file.seek(0)
    return response_file

它适用于:

from StringIO import StringIO

StringIO.StringIO在Python3中不存在(根据pylint),所以使用:

from io import StringIO

我得到一个错误:“TypeError:期望unicode参数,得到'str'”(这是在Python 2下运行 - 我还在准备基础,可以这么说,我不打算使用Python 3,直到我完成我可以在Python 2下进行大量准备和测试。)

通过一些实验,我尝试使用来自BytesIOio,但这给出了一个不同的错误“TypeError:'unicode'没有缓冲接口”。

显然,json.dump的Python2版本正在将str值写入提供的文件对象。我认为json.dump的Python3版本也写了str(即Unicode)值。

所以我的问题是:是否有一种简单的方法可以将JSON转储到与Python 2和3一起使用的StringIO内存缓冲区?

笔记

  1. 我意识到我可以使用json.dumps并将结果强制到StringIO所期望的任何类型,但这一切看起来都相当严厉。
  2. 我也在使用以下未来的导入作为移植过程的一部分: from __future__ import (unicode_literals, absolute_import, division, print_function)
  3. 目前,我正在考虑的解决方案是测试python版本并相应地导入不同版本的StringIO,但这会违反"Use feature detection instead of version detection"原则。
  4. 在我的大多数代码中,使用from io import StringIO似乎适用于我使用StringIO的情况。这是使用StringIOjson.dump的特定情况,这给我带来了一些问题。
python json python-3.x python-2.7 stringio
2个回答
0
投票

使用six's StringIO

from six.moves import StringIO


0
投票

如果您的问题是import语句,只需将其包装在try语句中:

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

你的其余代码应该按原样运行,至少你问题中提供的代码对我来说很合适。

© www.soinside.com 2019 - 2024. All rights reserved.