简体   繁体   中英

Pulling a certain value from a JSON string in python

I have set up a bot for Discord that is taking every users' messages and using a sentiment classifier to determine if a message is positive or negative. See the POST request to the text-processing.com API below.

Given a message 'I am extremely happy' , the API will return a response which is a string resembling JSON:

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

How can I convert this JSON object to a str, so that I can easily interact with its data?

@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)

The error code I am receiving is...

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'

Assuming that {"probability": {"neg": 0.32404484915164478, "neutral": 0.021768879244280313, "pos": 0.67595515084835522}, "label": "pos"} really is a string, you can call json.loads on it, and access its values like you would any ordinary dict.

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

Since you are using requests , you can achieve what you ask for by simply parsing the result directly as json instead that as text :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM