简体   繁体   English

用 Python 模拟 Bash jq

[英]Emulate Bash jq with Python

I have the following JSON in a file called data.json我在名为 data.json 的文件中有以下 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:当我运行这个 bash 命令时:

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?如何在 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.到目前为止,我已经能够使用 json 模块获取该信息,但我必须创建一个 for 循环才能这样做。 Is there anything built-in that I may have missed or am I stuck using a for loop?是否有任何我可能错过的内置内容,或者我是否一直在使用 for 循环?

Thanks.谢谢。

I'd like to thank @jarmod and @charles duffy for pointing me to the jq python module.我要感谢@jarmod 和@charles duffy 将我指向 jq python 模块。 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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