【问题标题】:Extract specific JSON field from Twitter streaming API using Python使用 Python 从 Twitter 流 API 中提取特定的 JSON 字段
【发布时间】:2021-10-04 03:22:26
【问题描述】:

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

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

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 json twitter


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢你——正是我需要的。
    • 如果我想返回 ['id'] 和 ['text'] 怎么办? twitter_variable = json_response['data']['id']['text'] 对我不起作用
    • 您可以提取包含“id”和“文本”字段的整个数据对象,如下所示:twitter_variable = json_response['data'],然后使用 twitter_variable['id '] 或 twitter_variable['text']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2019-04-19
    相关资源
    最近更新 更多