简体   繁体   English

如何在 Z23EEEB4347BDD26BDDZ6B7EE9A3B75 中的 api twitter 响应中获取 json 响应中的特定数据密钥

[英]how to get specific data key in json response from api twitter in python

I am trying to get attributes of only "id" and "text" in the result of response API Twitter.我试图在响应 API Twitter 的结果中仅获取“id”和“text”的属性。 But the below code result all key attribute.但是下面的代码导致所有关键属性。 How to get the data "id" and "text"?如何获取数据“id”和“text”?

from tweepy import Stream
from tweepy.streaming import StreamListener

class StdOutListener(StreamListener):

def on_data(self, data):
    try:
        with open('python2.json', 'a') as f:
            f.write(data)
            return True
    except BaseException as e:
        print("Error on_data: %s" % str(e))
    return True

def on_error(self, status_code):
    if status_code == 420:
        print(status_code)
        return False

if __name__ == '__main__':
    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l)
    hasil = stream.filter(track=['wedding','sunday'])

the result:结果:

 {"created_at":"Sun Apr 04 17:16:28,
 "id":1378758380722946049,
 "id_str":"1378758380722946049",
 "text":"Nonton wedding atta aurel jadi pen nikah",
 "source":"Twitter Web",
 "truncated":false,
 "in_reply_to_status_id":null,
 "in_reply_to_status_id_str":null
 }

the expected result just id and text预期的结果只是 id 和 text

{
 "id":1378758380722946049,
 "text":"Nonton wedding atta aurel jadi pen nikah"
}

It looks like you want to only write a JSON containing the id and text fields, so this modified version of your code will correctly take both those fields out of jsonData , create it's own new JSON only containing id and text ( newJSON ) and then write it to your file.看起来你只想写一个包含idtext字段的 JSON ,所以这个修改后的代码版本将正确地jsonData中取出这两个字段,创建它自己的新 JSON 只包含idtextnewJSON )然后写它到你的文件。

import json
from tweepy import Stream
from tweepy.streaming import StreamListener

class StdOutListener(StreamListener):

    def on_data(self, data):
        try:
            with open('python2.json', 'a') as f:
                jsonData = json.loads(data)
                id = jsonData["id"]
                text = jsonData["text"]
                newJSON = {'id': id, 'text': text}
                f.write(json.dumps(data))
                return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True

PS: Your code in your question has severe formatting problems, on_data and on_error should be indented under the StdOutListener class. PS:您问题中的代码有严重的格式问题, on_dataon_error应该在StdOutListener class 下缩进。

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

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