使用 Python 从 Twitter 流 API 中提取特定的 JSON 字段
Extract specific JSON field from Twitter streaming API using Python
我正在使用 Twitter 的流式传输 API 代码(找到 here)。我能够得到我想要的输出,这是一系列过滤结果。但是,我特别需要将 JSON 结果中的 'text' 字段分配给一个变量,但我无法想出正确的方法。
我已经隔离了 returns 流数据的代码部分,并在我 运行 时将其显示在终端中:
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))
我需要的只是获取返回的推文的文本部分。这是一个输出示例,注意我只需要将变量 - twitterVariable 设置为“文本”结果:
{
"data": {
"id": "125855555555",
"text": "hello this is a test"
},
"matching_rules": [
{
"id": 1234567890,
"tag": ""
}
]
}
由于您已经将响应加载到 python 的 dict 对象中,您可以使用 key 获取文本字段,如下所示:
twitter_variable = json_response['data']['text']
我正在使用 Twitter 的流式传输 API 代码(找到 here)。我能够得到我想要的输出,这是一系列过滤结果。但是,我特别需要将 JSON 结果中的 'text' 字段分配给一个变量,但我无法想出正确的方法。
我已经隔离了 returns 流数据的代码部分,并在我 运行 时将其显示在终端中:
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))
我需要的只是获取返回的推文的文本部分。这是一个输出示例,注意我只需要将变量 - twitterVariable 设置为“文本”结果:
{
"data": {
"id": "125855555555",
"text": "hello this is a test"
},
"matching_rules": [
{
"id": 1234567890,
"tag": ""
}
]
}
由于您已经将响应加载到 python 的 dict 对象中,您可以使用 key 获取文本字段,如下所示:
twitter_variable = json_response['data']['text']