Home > Net >  Read multiple keys from a JSON file in Python
Read multiple keys from a JSON file in Python

Time:01-27

I am a little stuck with the following task that I am trying to sort out as I am just learning Python. I need to sort out "city" from the json file that looks like:

[{
    "city": "Las Vegas",
    "operator": "",
    "browser_name": "chromium",
    "browser_version": "55",
    "country_code": "us",
    "country": "United States",
    "location_code": "2e4efc13-6a6a-45ba-a6aa-ec4eb1f4fb2b|north-america.na.us.west.lasvegas|chromium|55",
    "location_tier": "1"
}, {
    "city": "Las Vegas",
    "operator": "",
    "browser_name": "firefox",
    "browser_version": "46",
    "country_code": "us",
    "country": "United States",
    "location_code": "2e4efc13-6a6a-45ba-a6aa-ec4eb1f4fb2b|north-america.na.us.west.lasvegas|firefox|46",
    "location_tier": "1"
}, ...

I have the code like this:

import json, operator

file_path = './response.json'

with open(file_path) as f:
    data = json.loads(f.read())
    print(data[0]['city'])

The thing is that I need comma separated output to a console like "city, city, city...". Would appreciate any help! Thanks a lot!

CodePudding user response:

print(', '.join(item['city'] for item in data))

Also, have a look at this answer, using inflect package that will allow for properly constructed list in English, e.g. city, city, and city

CodePudding user response:

You are very close to the result. You can have a list like this. Code;

import json, operator
file_path = './response.json'
result = []
with open(file_path) as f:
    data = json.loads(f.read())
    for d in data:
        result.append(d['city'])
print(result)

Output; ['Las Vegas', 'Las Vegas']

  •  Tags:  
  • Related