如何在python中从api twitter获取json响应中的特定数据键
我试图在响应API Twitter的结果中只获取“id”和“text”属性。但下面的代码将生成所有键属性。如何获取数据“id”和“文本” 结果是:如何在python中从api twitter获取json响应中的特定数据键,python,json,api,twitter,web-crawler,Python,Json,Api,Twitter,Web Crawler,我试图在响应API Twitter的结果中只获取“id”和“text”属性。但下面的代码将生成所有键属性。如何获取数据“id”和“文本” 结果是: {"created_at":"Sun Apr 04 17:16:28, "id":1378758380722946049, "id_str":"1378758380722946049", "text":"Nonton wed
{"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
}
预期结果只是id和文本
{
"id":1378758380722946049,
"text":"Nonton wedding atta aurel jadi pen nikah"
}
看起来您只想编写一个包含id
和text
字段的JSON,因此此修改版本的代码将正确地从jsonData
中删除这两个字段,创建自己的新JSON,只包含id
和text
(newJSON
)然后将其写入您的文件
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
p.S.:您的问题中的代码存在严重的格式问题,上的数据
和上的错误
应该缩进到StdOutListener
类下
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