您如何比较python中的JSON列表,然后将该数据转换为HTML?

时间:2019-05-27 10:05:29

标签: python html json api flask

此问题有两个部分。我正在使用API​​密钥从http://api.open-notify.org/astros.json获取信息。这是有关国际空间站上每位宇航员的信息。我想取每个宇航员的名字,并将其与我在python中创建的列表进行比较。每个人都有名字,图片和简历。然后,我想使用HTML显示此信息。

我已经尝试过for循环,但是我不确定这样做如何。

url = 'http://api.open-notify.org/astros.json'
  response = urllib.request.urlopen(url)
  result = json.loads(response.read())

  print('People in Space: ', result['number'])

  people = result['people']

occupants = [
{'name': "Oleg Kononenko",
'bio': 'Oleg Dmitriyevich Kononenko is a Russian cosmonaut. He has flown to the International Space Station four times as a flight engineer and commander. Kononenko accumulated over 533 days in orbit during his first three long duration flights to ISS.',
    'img': 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Kononenko.jpg/220px-Kononenko.jpg',
},  
{'name': "David Saint-Jacques",
'bio': "David Saint-Jacques (born January 6, 1970) is a Canadian astronaut with the Canadian Space Agency (CSA). He is also an astrophysicist, engineer, and a physician.",
    'img': 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f8/David_Saint-Jacques_official_portrait.jpg/440px-David_Saint-Jacques_official_portrait.jpg',
},

]

@app.route("/occupants")
def occupants():
    return render_template('occupants.html', people=people)

1 个答案:

答案 0 :(得分:0)

@app.route("/occupants")
def list_occupants():
  result = json.loads(response.read())
  people = result["people"]
  people_with_exist_state = []

  for k in people:
     is_here = 0
     for k2 in occupants:
         if k['name'] == k2['name']:
            is_here = 1
     if is_here == 0:
         #name does not exist
         k['exist'] = 0
     else:
         # name exist
         k['exist'] = 1
     people_with_exist_state.append(k)
  return render_template('occupants.html', people=people_with_exist_state)

模板occupants.html

{% for item in people %}
<p>
{{ item['name'] }}: 
{% if item['exist']|int == 0 %}
Does not exist
{% else %}
exist
{% endif %}
</p>
{% endfor %}