user192749
user192749

Reputation: 257

How to create a list from json key:values in python3

I'm looking to create a python3 list of the locations from the json file city.list.json downloaded from OpenWeatherMaps http://bulk.openweathermap.org/sample/city.list.json.gz. The file passes http://json-validator.com/ but I can not figure out how to correctly open the file and create a list of values of key 'name'. I keep hitting json.loads errors about io.TextIOWrapper etc.

I created a short test file

[
    {
        "id": 707860,
        "name": "Hurzuf",
        "country": "UA",
        "coord": {
            "lon": 34.283333,
            "lat": 44.549999
        }

    }
    ,
    {
        "id": 519188,
        "name": "Novinki",
        "country": "RU",
        "coord": {
            "lon": 37.666668,
            "lat": 55.683334
        }

    }
]

Is there a way to parse this and create a list ["Hurzuf", "Novinki"] ?

Upvotes: 2

Views: 6842

Answers (1)

wencakisa
wencakisa

Reputation: 5968

You should use json.load() instead of json.loads(). I named my test file file.json and here is the code:

import json

with open('file.json', mode='r') as f:
    # At first, read the JSON file and store its content in an Python variable
    # By using json.load() function

    json_data = json.load(f)

    # So now json_data contains list of dictionaries
    # (because every JSON is a valid Python dictionary)

# Then we create a result list, in which we will store our names
result_list = []

# We start to iterate over each dictionary in our list
for json_dict in json_data:
    # We append each name value to our result list
    result_list.append(json_dict['name'])

print(result_list)  # ['Hurzuf', 'Novinki']

# Shorter solution by using list comprehension

result_list = [json_dict['name'] for json_dict in json_data]

print(result_list)  # ['Hurzuf', 'Novinki']

You just simply iterate over elements in your list and check whether the key is equal to name.

Upvotes: 7

Related Questions