Home > other >  How to extract attrbutes from json and make a list in python?
How to extract attrbutes from json and make a list in python?

Time:04-07

I would like to know how can I extract the attribute title from json file and make a python list based on the values.

[
{
 "title": "5280 Cafe At Rallysport",
 "streetAddress": "2727 29th St.",
 "addressLocality": "Boulder",
 "addressRegion": "CO",
 "postalCode": "80301",
 "phoneNumber": "720-526-1013",
"vendorCuisine": "Breakfast"
},
{
"title": "Ali Baba Grill Boulder",
"streetAddress": "3054 28th St",
"addressLocality": "Boulder",
"addressRegion": "CO",
"postalCode": "80304",
"phoneNumber": "303-440-1393",
"vendorCuisine": "Mediterranean"
}]

I would like to extract the attribute title and make a list from this values.

CodePudding user response:

You can use json.loads (or json.load if you are directly reading from a file) to convert a text (in json format) into a python object (nested lists/dicts), and then use list comprehension:

import json

text = '''[
{
 "title": "5280 Cafe At Rallysport",
 "streetAddress": "2727 29th St.",
 "addressLocality": "Boulder",
 "addressRegion": "CO",
 "postalCode": "80301",
 "phoneNumber": "720-526-1013",
"vendorCuisine": "Breakfast"
},
{
"title": "Ali Baba Grill Boulder",
"streetAddress": "3054 28th St",
"addressLocality": "Boulder",
"addressRegion": "CO",
"postalCode": "80304",
"phoneNumber": "303-440-1393",
"vendorCuisine": "Mediterranean"
}]'''

output = [d['title'] for d in json.loads(text)]
print(output) # ['5280 Cafe At Rallysport', 'Ali Baba Grill Boulder']

If your json text is stored in, say, restaurants.json, then:

with open('restaurants.json', 'r') as f:
    output = [d['title'] for d in json.load(f)]
  • Related