Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

How do I get countries and states from a JSON in Python to a dropdown list in HTML?

I am new to python and really need a solid walkthrough for this:

I have all the data from a JSON file called countries.json which contain country name and states.

Here's a small snippet example from the first one:

[
  {
    "code2": "AF",
    "code3": "AFG",
    "name": "Afghanistan",
    "capital": "Kabul",
    "region": "Asia",
    "subregion": "Southern Asia",
    "states": [
      {
        "code": "BDS",
        "name": "Badakhshān",
        "subdivision": null
      },
      {
        "code": "BGL",
        "name": "Baghlān",
        "subdivision": null
      }

So, I have all the countries and all the states for those countries and I would like them to go to an HTML file with this:

<select name="country" id="country">
<option value="">Select Country</option>
</select>
<select name="state" id="state">
<option value="">Select State</option>
</select>

From there I will use it to update a database with the user selection which is set up, currently, to accept "country" and "state".

I have checked the JSON file works with a simple countries.py code:

import json

with open('countries.json', encoding="utf8") as f:
  data = json.load(f)

print(data)

And that's fine. So I can print the entire thing no problems in the terminal. But how do I now separate so it only prints "country" and then from that country prints their "state" and then send that information via the HTML page with the current name and id?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, not as difficult as I thought. I had most of the data there:

with open('countries.json', encoding="utf8") as f:
               country = json.load(f)
 
return render_template("edit_profile.html", profile=user_profile, countries=country)

<select name="country" id="country">
{% for country in countries %}
<option>{{ country.name }}</option>
{% endfor %}
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...