从python中的JSON字符串中提取特定值

时间:2018-07-30 17:06:42

标签: python json python-3.x

我为Discord设置了一个机器人,该机器人可以接收每个用户的消息,并使用情感分类器确定消息是肯定的还是否定的。请参见下面的text-processing.com API的POST请求。

给出消息'I am extremely happy',API将返回响应,该响应是类似于JSON的字符串:

{"probability": {"neg": 0.32404484915164478, "neutral": 0.021768879244280313, "pos": 0.67595515084835522}, "label": "pos"}

如何将该JSON对象转换为str,以便可以轻松地与其数据进行交互?

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    with open('data.txt', 'a') as f:
        print(repr(message.content), file=f)
        response = requests.post('http://text-processing.com/api/sentiment/', {
            'text': message.content
        }).json()
        print(response, file=f)
        d = json.loads(response)
        print(d["probability"]["pos"], file=f)
        f.close()

    await bot.process_commands(message)

我收到的错误代码是...

File "/Users/enzoromano/PycharmProjects/NewDiscordBot/NewBot.py", line 44, in on_message
    d = json.loads(response)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 348, in loads
    'not {!r}'.format(s.__class__.__name__))
TypeError: the JSON object must be str, bytes or bytearray, not 'dict'

2 个答案:

答案 0 :(得分:3)

假设{"probability": {"neg": 0.32404484915164478, "neutral": 0.021768879244280313, "pos": 0.67595515084835522}, "label": "pos"}确实是一个字符串,则可以在其上调用json.loads,并像访问普通字典一样访问其值。

>>> s = """{"probability": {"neg": 0.32404484915164478, "neutral": 0.021768879244280313, "pos": 0.67595515084835522}, "label": "pos"}"""
>>> import json
>>> d = json.loads(s)
>>> d["probability"]["pos"]
0.6759551508483552

答案 1 :(得分:3)

由于您使用的是requests,因此只需将结果直接解析为json而不是text,就可以实现所需的目标:

response = requests.post('http://text-processing.com/api/sentiment/', {
    'text': message.content
}).json()