在下面的构造中,我试图通过我的web服务传递一个JSON对象。作为一个新的需求,我必须在下面的代码中传递一个dictionary对象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)
如果取消注释该行,则会出现以下错误:
^{pr2}$
在JSON中,字典键必须是字符串。您有一个Python字典
sent
,希望将其序列化为JSON。这将失败,因为您的字典sent
的键不是字符串,而是textblob.blob.Sentence
实例。在如果有意义,可以将代码更改为:
或者,您可以定制pythonjson编码器来知道如何序列化TextBlob语句。在
相关问题 更多 >
编程相关推荐