json.dumps()适用于python 2.7但不适用于python 3

时间:2016-01-20 19:07:07

标签: python json python-2.7 python-3.x pickle

我有以下代码:

import json

src_vol1 = {'provider_id':'src1'}
src_vol2 = {'provider_id':'src2'}
get_snapshot_params = lambda src_volume, trg_volume: {
    'volumeId': src_volume['provider_id'],
    'snapshotName': trg_volume['id']}
trg_vol1 = {'id':'trg1'}
trg_vol2 = {'id':'trg2'}
src_vols = [src_vol1, src_vol2]
trg_vols = [trg_vol1, trg_vol2]
snapshotDefs = map(get_snapshot_params , src_vols, trg_vols)
params = {'snapshotDefs': snapshotDefs}
json.dumps(params)

我需要它在Python3和Python2.7上工作,但在Python3上我得到

Traceback (most recent call last):   
  File "./prog.py", line 16, in <module>
  File "/usr/lib/python3.4/json/__init__.py", line 230, in dumps
      return _default_encoder.encode(obj)
  File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
      chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
      return _iterencode(o, 0)
  File "/usr/lib/python3.4/json/encoder.py", line 173, in default
     raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <map object at 0xb72a1a0c> is not JSON serializable

我试图把dict()放在params周围,但它没有用。 有什么不同?我在文档中找不到任何内容。

2 个答案:

答案 0 :(得分:4)

python2和3之间的

map behaves differently

要重现python2行为,请将list(map(...))替换为map

这仍然可以在python2中运行,但是在python2中,它会使try: from itertools import imap as map # py2 except ImportError: pass # py3, map is already defined apropriately 返回的列表有一个无意义的额外副本,这会占用更多内存并运行得更慢。

为避免这种情况,您可以尝试以下方法:

{{1}}

答案 1 :(得分:0)

或者您也可以检查系统版本,然后根据系统版本将map重新定义为map_

import sys

ver = sys.version[:3] 

if ver < '3': #Python 2
    map_ = map #use same map method
elif ver >= '3': #Python 3
    map_ = lambda f,x : list(map(f,x))

snapshotDefs = map_(get_snapshot_params , src_vols, trg_vols)