在 Python 3.7 中序列化为 JSON 字符串 tracemalloc

Serialize to JSON string tracemalloc in Python 3.7

我必须将 tracemalloc 的结果序列化为 JSON 字符串。

current_mem, peak_mem = tracemalloc.get_traced_memory()
overhead = tracemalloc.get_tracemalloc_memory()
stats = tracemalloc.take_snapshot().statistics('traceback')[:top]

summary = "traced memory: %d KiB  peak: %d KiB  overhead: %d KiB" % (
    int(current_mem // 1024), int(peak_mem // 1024), int(overhead // 1024)
)

logging.info("%s", summary)

out_lines = [ summary ]
for trace in stats:
    out_lines.append("---")
    out_lines.append( "%d KiB in %d blocks" % (int(trace.size // 1024), int(trace.count)) )

    logging.info("%s", out_lines)

    out_lines.extend( trace.traceback.format() )

out_lines.append('')

data = {}
data['traceback'] = '\n'.join(out_lines).encode('utf-8')

res = json.dumps(data)

print(res)

当我将数据转储到 JSON 时,我得到一个

Object of type bytes is not JSON serializable

从日志中我可以看到字符串输出:

2020-01-08 11:54:25 - INFO - traced memory: 35 KiB  peak: 91 KiB  overhead: 31 KiB
2020-01-08 11:54:25 - INFO - ['traced memory: 35 KiB  peak: 91 KiB  overhead: 31 KiB', '---', '1 KiB in 4 blocks']

然后在循环中:

2020-01-08 11:54:26 - ERROR - ['traced memory: 35 KiB  peak: 91 KiB  overhead: 31 KiB', '---', '1 KiB in 4 blocks', '  File "/usr/local/lib/python3.7/site-packages/tornado/routing.py", line 256', '    self.delegate.finish()', '  File "/usr/local/lib/python3.7/site-packages/tornado/web.py", line 2195', '    self.execute()', '  File "/usr/local/lib/python3.7/site-packages/tornado/web.py", line 2228', '    **self.path_kwargs)', '  File "/usr/local/lib/python3.7/site-packages/tornado/gen.py", line 326', '    yielded = next(result)', '  File "/usr/local/lib/python3.7/site-packages/tornado/web.py", line 1590', '    result = method(*self.path_args, **self.path_kwargs)', '  File "/tornado/handlers/memTraceHandler.py", line 56', '    self.write(json.dumps(response.getData()))', '---', '0 KiB in 2 blocks']

那么我无法序列化的 b"" 字符串是哪个?

正在此处创建 bytes 对象:

data['traceback'] = '\n'.join(out_lines).encode('utf-8')

这就是调用 encode 的作用。

只需执行:

data['traceback'] = '\n'.join(out_lines)

它会很好地倾倒出来。