Search code examples
pythonjsontwitter

Extract specific JSON field from Twitter streaming API using Python


I am using Twitter's streaming API code (found here). I am able to get my desired output which is a series of filtered results. However, I specifically need to assign the 'text' field from the JSON result to a variable and I am unable to come up with the right way to do it.

I have isolated the part of the code that returns the streaming data and display it in the terminal when I run it:

for response_line in response.iter_lines():
    if response_line:
        json_response = json.loads(response_line)
        print(json.dumps(json_response, indent=4, sort_keys=True))

What I need is to just get the text part of the tweet that is returned. Here's an output example, noting I only need to set a variable - twitterVariable to the "text" result:

{
"data": {
    "id": "125855555555",
    "text": "hello this is a test"
},
"matching_rules": [
    {
        "id": 1234567890,
        "tag": ""
    }
]
}

Solution

  • As you have already loaded the response into dict object of python, you can use key to get the text field as below:

    twitter_variable = json_response['data']['text']