Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Extract and concat json data

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading