简体   繁体   中英

Emulate Bash jq with Python

I have the following JSON in a file called data.json

{
  "tenant_admins": [
    {
      "is_user": true,
      "id": "id-1",
      "user_id": "P000216",
      "email": "test1@test.com",
      "first_name": "Test",
      "last_name": "One",
      "display_name": "Test One",
      "status": "active",
      "roles": {
        "manage_access": true,
        "manage_idp": true
      }
    },
    {
      "is_user": false,
      "id": "id-2",
      "user_id": "P000218",
      "email": "test2@test.com",
      "first_name": "Test",
      "last_name": "Two",
      "display_name": "Test Two",
      "status": "active",
      "roles": {
        "manage_access": true,
        "manage_idp": true
      }
    },
    {
      "is_user": true,
      "id": "id-3",
      "user_id": "P000230",
      "email": "test3@test.com",
      "first_name": "Test",
      "last_name": "Three",
      "display_name": "Test Three",
      "status": "active",
      "roles": {
        "manage_access": true,
        "manage_idp": true
      }
    }
  ]
}

When I run this bash command:

cat data.json| jq ".tenant_admins[].id"

I get the following response that I expect:

"id-1"
"id-2"
"id-3"

How can I do the same operation in Python? So far I've been able to grab that information using the json module, but I have to create a for loop to do so. Is there anything built-in that I may have missed or am I stuck using a for loop?

Thanks.

I'd like to thank @jarmod and @charles duffy for pointing me to the jq python module. After some poking around, I was able to create the following:

import json
import jq

with open('data.json') as f:
    data = json.load(f)

ids = jq.compile('.tenant_admins[].id').input(data).all()

# Print the extracted names
print(ids)

This results in:

['id-1', 'id-2', 'id-3']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM