无法解决TypeError:“地图”类型的对象不可JSON序列化

时间:2019-07-23 05:05:13

标签: json python-3.x python-3.6

在python 3.6中使用json.dumps将映射解析为字符串时出错

x = {'id_str': '639035115457388544', 'video': False, 'photo': False, 'link': True, 'hashtags': <map object at 0x7f1762ab9320>, 'coordinates': None, 'timestamp_ms': 1441218018000, 'text': 'Police suspected hit-and-run', 'user': {'id': 628694263, 'name': 'Beth LeBlanc', 'friends_count': 235, 'verified': False, 'followers_count': 654, 'created_at': 1341631106000, 'time_zone': None, 'statuses_count': 3966, 'protected': 3966}, 'mentions': [], 'screen_name': 'THBethLeBlanc', 'reply': None, 'tweet_type': 'Tweet', 'mentionedurl': None, 'possibly_sensitive': False, 'placename': '', 'sentiments': 'Undefined'}

print(json.dumps(x))
TypeError: Object of type 'map' is not JSON serializable

2 个答案:

答案 0 :(得分:0)

您的x出现错误,因为主题标签键没有相应的值。在这里是固定的: https://repl.it/repls/SubtleLovableSystemadministrator

答案 1 :(得分:0)

我不知道如何为'hashtags'增值,但是下面的示例将帮助您稍微解决一下问题。用list()包围地图对象。

>>> import json
>>> 
>>> some_map_value = map([],[])
>>> some_map_value
<map object at 0x7f380a75a850>
>>> 
>>> x = {'hashtags': some_map_value}
>>> x
{'hashtags': <map object at 0x7f380a75a850>}
>>> 
>>> json.dumps(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.7/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.7/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.7/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type map is not JSON serializable
>>> 
>>> list(some_map_value)
[]
>>> x = {'hashtags': list(some_map_value)}  # surround your map object with list
>>> json.dumps(x)
'{"hashtags": []}'

有关更多信息,请检查此Getting a map() to return a list in Python 3.x Ask Question问题。如果您不喜欢这个,请对此答案发表评论。

更新:只需检查您的评论即可。用list()包围map(lambda x: x['text'],doc['entities']['hashtags']),就像list(map(lambda x: x['text'],doc['entities']['hashtags']))

if doc['entities'].get('media'):
    tweet['photo'] = True
if doc.get('extended_entities'):
    tweet[doc['extended_entities']['media'][0]['type']] = True
    tweet['mediaurl'] = doc['extended_entities']['media'][0]['media_url']
if doc['entities'].get('urls'):
    tweet['link'] = True
    tweet['hashtags'] = list(map(lambda x: x['text'],doc['entities']['hashtags']))
    tweet['coordinates'] = doc['coordinates']