Home > other >  Python: Extract and concat json data
Python: Extract and concat json data

Time:04-06

I have this json structure:

[
{
    "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 title, streetAddress, addressLocality and postal Code and finally have this format for each one.

final_address = 5280 Cafe At Rallysport, 2727 29th St., Boulder , 80301

I am not sure how can I do this.

CodePudding user response:

One option is to create a list of the keys you want to get, then iterate over this list to lookup the values and join them:

keys = ['title', 'streetAddress', 'addressLocality', 'postalCode']
out = [', '.join(d[k] for k in keys) for d in data]

Another option that is possibly faster than the one above is to map operator.itemgetter to get the values, then map join:

from operator import itemgetter
out = [*map(', '.join, map(itemgetter(*keys), data))]

Output:

['5280 Cafe At Rallysport, 2727 29th St., Boulder, 80301',
 'Ali Baba Grill Boulder, 3054 28th St, Boulder, 80304']
  • Related