简体   繁体   中英

json.dumps() works on python 2.7 but not on python 3

I have the following code:

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)

I need it work on both Python3 and Python2.7, but on Python3 I get

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

I tried to put dict() around the params but it didn't work. What is the difference? I didn't find anything in the documentation.

map behaves differently between python2 and 3.

To reproduce the python2 behavior, replace map(...) with list(map(...)) .

This still works in python2, but in python2 it makes a pointless extra copy of the list returned by map , which can consume more memory and run slower.

To avoid it, you can try something like:

try:
    from itertools import imap as map  # py2
except ImportError:
    pass # py3, map is already defined apropriately

Or you can also check for system version and then re-define map into map_ based on system version:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM