Hyperion
Hyperion

Reputation: 2625

Python - Match json object with multiple conditions

urls = ['http://google.com', 'http://yandex.com']

jobs = {
    "jobs": [{
        "id": "4535765",
        "urls": [{
            "url": "http://google.com",
            "status": "OK"
        }, {
            "url": "http://yandex.com",
            "status": "OK"
        }]
    }, {
        "id": "4535756",
        "urls": [{
            "url": "http://example.com",
            "status": "OK"
        }, {
            "url": "http://google.it",
            "status": "OK"
        }]
    }]
}

I need to match the job id that has as urls all the urls in urls.

job_id = [j['id'] for j in jobs['jobs'] if all(u in jobs['urls'] for u in urls)]

Of course it doesn't work, cant think a way to interact with every url in urls.

Upvotes: 0

Views: 306

Answers (1)

wpercy
wpercy

Reputation: 10090

You were really close, you just weren't actually grabbing the url values from the url object within the jobs. Try this:

job_ids = [j['id'] for j in jobs['jobs'] if all(u['url'] in urls for u in j['urls'])]

Upvotes: 2

Related Questions