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

2024-05-02 01:12:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Twitter的流式API代码(找到here)。我能够得到我想要的输出,这是一系列过滤结果。但是,我特别需要将JSON结果中的“text”字段指定给一个变量,我无法找到正确的方法

我已经隔离了返回流数据的代码部分,并在运行时将其显示在终端中:

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

我需要的只是获取返回的tweet的文本部分。下面是一个输出示例,我只需要将变量-twitterVariable设置为“text”结果:

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

1条回答
网友
1楼 · 发布于 2024-05-02 01:12:18

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

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

相关问题 更多 >