如何将dictionary添加到json对象中



在下面的构造中,我试图通过web服务传递一个JSON对象。作为一个新的需求,我必须在下面的代码中传递一个字典对象sent。你能指导我如何将字典添加到JSON对象中吗?

if plain_text is not None:
        blob = TextBlob(plain_text)
        sentiment = TextBlob(plain_text)
        sent = {}
        for sentence in blob.sentences:
            sent[sentence] =sentence.sentiment.polarity
        print sent
        return json.dumps(
            {'input' : plain_text, 
             'Polarity': sentiment.polarity,                 
             #'sent': json.dumps(sent) # this is where I am stuck as this 'sent' is a dict
             },
            indent=4)

如果我取消注释行,我会得到以下错误:

Exception:
TypeError('keys must be a string',)
Traceback:
Traceback (most recent call last):
  File "C:Python27libsite-packagesbottle-0.12.7-py2.7.eggbottle.py", line 862, in _handle
    return route.call(**args)
  File "C:Python27libsite-packagesbottle-0.12.7-py2.7.eggbottle.py", line 1729, in wrapper
    rv = callback(*a, **ka)
  File "C:UsershpDesktopRealPyWebServicesbottleserver_bckup.py", line 53, in sentimentEngine
    'sent': json.dumps(sent),
  File "C:Python27libjson__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:Python27libjsonencoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:Python27libjsonencoder.py", line 264, in iterencode
    return _iterencode(o, 0)
TypeError: keys must be a string

在JSON中,字典键必须是字符串。您有一个Python字典sent,希望将其序列化为JSON。这会失败,因为字典sent中的键不是字符串,而是textblob.blob.Sentence实例。

如果有意义的话,你可以把你的代码改为:

    for sentence in blob.sentences:
        sent[str(sentence)] = sentence.sentiment.polarity

或者,您可以自定义Python JSON编码器来了解如何序列化TextBlob语句。

最新更新