使用Flask显示stackOverflow API JSON数据

时间:2012-03-28 03:50:42

标签: python json flask python-requests

我一直在尝试从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]和声誉。我有什么选择来完成这项工作?

  

{ “项”:[{ “USER_ID”:540028 “USER_TYPE”: “注册”, “CREATION_DATE”:1292207782, “DISPLAY_NAME”: “Fuchida”, “profile_image”:“HTTP://www.gravatar的.com /化身/ 6842025a595825e2de75dfc3058f0bee d = identicon&安培; R = PG”, “信誉?”:13, “reputation_change_day”:0 “reputation_change_week”:0 “reputation_change_month”:0 “reputation_change_quarter”:0 “reputation_change_year”: 0, “时代”:24, “last_access_date”:1332905685, “LAST_MODIFIED_DATE”:1332302766, “is_employee”:假的, “链接”: “http://stackoverflow.com/users/540028/fuchida”, “WEBSITE_URL”: “http://blog.Fuchida.me”, “位置”:“明尼阿波利斯   MN”, “ACCOUNT_ID”:258084 “badge_counts”:{ “黄金”:0, “银”:0, “铜”:3}}], “quota_remaining”:282, “quota_max”:300, “has_more” :假}

1 个答案:

答案 0 :(得分:4)

使用 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)