【问题标题】:How to add dictionary to json object如何将字典添加到json对象
【发布时间】:2014-12-16 07:20:12
【问题描述】:

在下面的构造中,我试图通过我的 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:\Python27\lib\site-packages\bottle-0.12.7-py2.7.egg\bottle.py", line 862, in _handle
    return route.call(**args)
  File "C:\Python27\lib\site-packages\bottle-0.12.7-py2.7.egg\bottle.py", line 1729, in wrapper
    rv = callback(*a, **ka)
  File "C:\Users\hp\Desktop\RealPy\WebServices\bottle\server_bckup.py", line 53, in sentimentEngine
    'sent': json.dumps(sent),
  File "C:\Python27\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python27\lib\json\encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python27\lib\json\encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
TypeError: keys must be a string

【问题讨论】:

  • 为什么不 {.., 'sent':sent} ?
  • 如果您只是取消注释该行,会发生什么?
  • print sent 打印什么?
  • 您好 John,print sent 正确打印键值对。当我尝试将它包含在 json 对象中时,问题就出现了。 @Burhan:我现在也添加了错误消息。

标签: python json python-2.7 dictionary textblob


【解决方案1】:

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

如果有意义,您可以将代码更改为:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-21
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    相关资源
    最近更新 更多