其他分享
首页 > 其他分享> > 使用Flask显示stackOverflow API JSON数据

使用Flask显示stackOverflow API JSON数据

作者:互联网

我一直在尝试从StackOverflow API检索的JSON数据中显示我的用户名和信誉.

我正在使用python模块请求检索数据.
这是代码

from flask import Flask,jsonify
import requests
import simplejson 
import json

app = Flask(__name__)

@app.route("/")
def home():
    uri = "https://api.stackexchange.com/2.0/users?   order=desc&sort=reputation&inname=fuchida&site=stackoverflow"
    try:
        uResponse = requests.get(uri)
    except requests.ConnectionError:
       return "Connection Error"  
    Jresponse = uResponse.text
    return Jresponse

if __name__ == "__main__":
    app.run(debug = True)

未完成的导入是我需要完成的工作,但似乎不知道如何完成它.
以下是返回浏览器的内容,我只想显示用户名[display_name]和信誉.我必须有什么选择才能完成此任务?

{“items”:[{“user_id”:540028,”user_type”:”registered”,”creation_date”:1292207782,”display_name”:”Fuchida”,”profile_image”:”http://www.gravatar.com/avatar/6842025a595825e2de75dfc3058f0bee?d=identicon&r=PG”,”reputation”:13,”reputation_change_day”:0,”reputation_change_week”:0,”reputation_change_month”:0,”reputation_change_quarter”:0,”reputation_change_year”:0,”age”:24,”last_access_date”:1332905685,”last_modified_date”:1332302766,”is_employee”:false,”link”:”https://stackoverflow.com/users/540028/fuchida”,”website_url”:”http://blog.Fuchida.me”,”location”:”Minneapolis
MN”,”account_id”:258084,”badge_counts”:{“gold”:0,”silver”:0,”bronze”:3}}],”quota_remaining”:282,”quota_max”:300,”has_more”:false}

解决方法:

使用json.loads()读取和解码数据.

from flask import Flask,jsonify
import requests
import simplejson 
import json

app = Flask(__name__)

@app.route("/")
def home():
    uri = "https://api.stackexchange.com/2.0/users?   order=desc&sort=reputation&inname=fuchida&site=stackoverflow"
    try:
        uResponse = requests.get(uri)
    except requests.ConnectionError:
       return "Connection Error"  
    Jresponse = uResponse.text
    data = json.loads(Jresponse)

    displayName = data['items'][0]['display_name']# <-- The display name
    reputation = data['items'][0]['reputation']# <-- The reputation

    return Jresponse

if __name__ == "__main__":
    app.run(debug = True)

标签:flask,python-requests,json,python
来源: https://codeday.me/bug/20191101/1984247.html