简体   繁体   English

使用 Python 从 Twitter 流 API 中提取特定的 JSON 字段

[英]Extract specific JSON field from Twitter streaming API using Python

I am using Twitter's streaming API code (found here ).我正在使用 Twitter 的流 API 代码(在这里找到)。 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.但是,我特别需要将 JSON 结果中的“文本”字段分配给一个变量,但我无法想出正确的方法来做到这一点。

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:这是一个输出示例,注意我只需要设置一个变量 - twitterVariable 到“文本”结果:

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

由于您已经将响应加载到 python 的 dict 对象中,您可以使用 key 获取文本字段,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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