Skip to main content
 首页 » 编程设计

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

2025年05月04日1598°冷暖

我已经为 Discord 设置了一个机器人,它接收每个用户的消息并使用情绪分类器来确定消息是正面的还是负面的。请参阅下面对 text-processing.com API 的 POST 请求。

给定一条消息“我非常高兴”,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' 

请您参考如下方法:

由于您使用的是 requests ,您可以通过简单地将结果直接解析为 json 而不是 text 来实现您的要求:

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