Python在没有文件的情况下解压内存中的gzip数据

标签 python json gzip compression stringio

我已经从 HTTP 回复中压缩了数据。我有以下代码:

def gzipDecode(self, content):
    import StringIO
    import gzip

    outFilePath = 'test'

    compressedFile = StringIO.StringIO(content)
    decompressedFile = gzip.GzipFile(fileobj=compressedFile)
    with open(outFilePath, 'w') as outfile:
        outfile.write(decompressedFile.read())

    data = ''
    with open(outFilePath, 'r') as myfile:
        data=myfile.read().replace('\n', '')

    return data

解压缩输入的 gzip 压缩内容并返回字符串(http 回复是 gzip 压缩的 json)。 - 它有效。

但我需要它而不创建测试 文件 - 全部在内存中。

我修改为:

def gzipDecode(self, content):
    import StringIO
    from io import BytesIO
    import gzip

    outFile = StringIO.StringIO()

    compressedFile = StringIO.StringIO(content)
    decompressedFile = gzip.GzipFile(fileobj=compressedFile)

    outFile.write(decompressedFile.read())
    outFile.flush()

    data = outFile.read().replace('\n', '')
    print "_" + data + "_"
    return data

但它在解析 json 时崩溃(gzipDecode 产生空输出):

Traceback (most recent call last):
__
  File "/usr/lib/python2.7/SocketServer.py", line 593, in process_request_thread

    self.finish_request(request, client_address)
----------------------------------------
  File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
Exception happened during processing of request from ('10.123.66.3', 39853)
    self.RequestHandlerClass(request, client_address, self)
----------------------------------------
  File "/usr/lib/python2.7/SocketServer.py", line 649, in __init__
    self.handle()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 340, in handle
    self.handle_one_request()
  File "/usr/lib/python2.7/BaseHTTPServer.py", line 328, in handle_one_request
    method()
  File "/tmp/test_server.py", line 92, in do_POST
    data = json.loads(file_content)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

我做错了什么?

最佳答案

在阅读之前你需要回到起点:

outFile.write(decompressedFile.read())
outFile.flush()
outFile.seek(0)

data = outFile.read().replace('\n', '')

关于Python在没有文件的情况下解压内存中的gzip数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36282037/

相关文章:

python - 保持套接字在线程中打开,并从Main发送命令

objective-c - Json获取参数无法在iOS上访问

java - jackson - 从 GET Api 返回 JSON POJO 时未找到 MessageBodyWriter

python - 为什么 pickle + gzip 在重复数据集上优于 h5py?

javascript - 如果我们不支持 IE6,那么为 IE 压缩 Javascript 文件是否有意义?

python - 如何使用 sqlalchemy 查找每个 "n"的最新条目

python - 在python中查找并打印字符串中的所有数字

python - 如何最好地捕捉 OSX 的 sleep 和恢复事件?

php - json_encode 不双引号 NULL ; cocoa touch 不当

php - 在 PHP 中解码通过 cURL 检索的 gzip 网页