【问题标题】:Create in python a dictionary from JSON url在python中从JSON url创建一个字典
【发布时间】:2016-11-17 19:13:57
【问题描述】:

我想从 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 %}

【问题讨论】:

  • 您能否展示一下您是如何尝试使用模板中的数据的?
  • 我只是编辑它@c3st7n

标签: python json url


【解决方案1】:

因为我不想激活烧瓶,所以我把我的答案打断了。

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 的 requests 模块。我将结果传递给数据变量。我使用了一个 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)

【讨论】:

  • 我也会尝试这个选项,但理解起来有点复杂
  • @AdriánVázquez 我看不出它有多复杂。它比您的示例使用更少的行,更少的对话和零列表构建。我将更新我的示例以仅包含可以复制和粘贴的代码。
【解决方案2】:

您正在将数组转换为 dict,但随后您将 dict 放入长度为 1 的数组中,唯一的对象是 dict。问题是,您的模板期望数组中的每个元素都是一个字典,带有一个“位置”字段。

您可以从转换data = dict(location=array) 中删除方括号,然后将模板更新为只执行for d in data.location,或者您可以更新追加调用以追加字典项而不是字符串:array.append({"location": i["location"]})

【讨论】:

  • 有效!但只是第一个,我无法让它工作第二个,非常感谢!
  • 第二个你将作为数据对象传入数组中。该数组本质上是一个字典列表,因此模板将遍历每个字典,然后选择位置字段。
【解决方案3】:

几件事:

  1. url 是一个字节对象,它不适用于json.loads(str)。因此,您必须通过 json.loads(str(url,'utf-8')) 或 @Mattia 建议的方法将其转换为字符串

  2. @louhoula 是正确的。但是,如果您希望 data 是一个字典列表,每个字典都包含一个 location 键(这是我通过查看您的模板得到的想法),那么您应该将模板中的 d.location 更改为:

    {% if 'location' in d.keys(): %}

    {{ d['location'] }}
    

    {% else %} &lt;p class="lead"&gt; You should not see this msg, otherwise, check the code again. &lt;/p&gt;

    {% endif %}

【讨论】:

    【解决方案4】:

    试试这个:

        import urllib.request, json
        url = 'https://api.openaq.org/v1/locations?country=GB'
        response = urllib.request.urlopen(url);
        decoded_data = json.loads(response.read().decode("utf-8"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-15
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多