Skip to main content
 首页 » 编程设计

python之在 python 中创建来自 JSON url 的字典

2025年05月04日15zfyouxi

我想在 Python 中从 JSON API url 创建一个位置的 HTML 列表。

@app.route('/api') 
def api(): 
url = urlopen('https://api.openaq.org/v1/locations?country=GB').read() 
#encoded we do not need it 
#encoded_data = json.dumps(url) 
 
#create variables 
array = [] 
data = {} 
 
#decoded 
decoded_data = json.loads(url) 
 
#we search for result each entry 
for i in decoded_data["results"]: 
    #append every entry to an array 
    array.append(i["location"]) 
#we create a dictionary from that array created which has a variable (for jinja2) called location 
data = [dict(location=array)] 
return render_template('api.html', data=data) 

但是我没有接收到每个元素,而是得到了这个:

[u'Aberdeen', u'Aberdeen Union Street Roadside', u'Aberdeen Wellington Road', u'Armagh Roadside', u'Aston Hill', u'Auchencorth Moss', u'Ballymena Ballykeel', u'Barnsley Gawber', u'Barnstaple A39', u'Bath Roadside', u'Belfast Centre', u"Belfast Stockman's Lane", u'Billingham', u'Birkenhead Borough Road', u'Birmingham A4540 Roads... 

编辑:模板

 {% if data %} 
    <ul> 
    {% for d in data %} 
      <li>{{ d.location }}</li> 
    {% endfor %} 
    </ul> 
  {% else %} 
    <p class="lead"> 
      You should not see this msg, otherwise, check the code again. 
    </p> 
  {% endif %} 

请您参考如下方法:

我把我的答案分解了一点,因为我不想激活 flask 。

import requests 
 
def api(): 
    res = requests.get('https://api.openaq.org/v1/locations?country=GB') 
    data = res.json()['results'] 
    return data 
 
 
@app.route('/api') 
def api(): 
    res = requests.get('https://api.openaq.org/v1/locations?country=GB') 
    try: 
        data = res.json()['results'] 
    except KeyError: 
        data = None 
    # this is the logic that you use in your template, I moved it out here 
    # cause i don't want to start a flask instance 
    for d in data: 
        print d['location'] 
    return render_template('api.html', data=data) 
 
api() 

基本上我使用可以返回 json 的请求模块。我将结果传递给数据变量。我使用了一个 for 循环来演示它如何在您的模板中工作。基本上将数据作为字典传入并通过迭代 d['location']

获取位置

所以要使用的代码是

import requests 
 
@app.route('/api') 
def api(): 
    res = requests.get('https://api.openaq.org/v1/locations?country=GB') 
    try: 
        data = res.json()['results'] 
    except KeyError: 
        data = None 
    return render_template('api.html', data=data)