简体   繁体   English

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

[英]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 我需要它在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

I tried to put dict() around the params but it didn't work. 我试图把dict()放在params周围,但它不起作用。 What is the difference? 有什么不同? I didn't find anything in the documentation. 我没有在文档中找到任何内容。

map behaves differently between python2 and 3. map在python2和3之间的行为有所不同

To reproduce the python2 behavior, replace map(...) with list(map(...)) . 要重现python2行为,请将map(...)替换为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. 这仍然可以在python2中运行,但是在python2中它会使map返回的列表有一个无意义的额外副本,这会占用更多的内存并且运行速度更慢。

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: 或者您也可以检查系统版本,然后根据系统版本将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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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