【问题标题】:How to extract a field from each object in an array with jq?如何使用jq从数组中的每个对象中提取一个字段?
【发布时间】:2018-01-24 15:27:52
【问题描述】:

我执行了一个 cURL 请求来获取我们 Gitlab 服务器中的所有用户,就像这样。

$ curl -H "Private-Token: a;sldkfja;slkdfj" https://gitlab.domain.com/api/v3/users?active=true > my_file.json

和(部分)my_file.json 看起来像:

[
  {
    'username' : 'jdoe',
    'name' : 'John Doe',
    ...
  },
  {
    'username' : 'jadoe',
    'name' : 'Jane Doe',
    ...
  }
]

我将响应存储在my_file.json 中。如何使用jq 获取所有username 值?

$ cat my_file.json | jq -r 'what to put here?'

【问题讨论】:

  • 如果这是实际的 cURL 响应或文件内容的样子,则说明您的 JSON 无效。
  • 您向我们展示了源数据,您希望输出数据是什么样的?
  • @JAAulde,我想要一个可以让我轻松解析所有用户名的输出。
  • 你所陈述的目标太主观了。请在您的问题中提供所需输出的示例格式。
  • 我不认为这是一个糟糕的要求。精确的输出格式并不重要——他显然是在尝试使用 jq 语法(如标题所述)“从数组中的每个对象中提取一个字段”。被接受的回答者清楚地知道他(和我)想要什么。

标签: json jq


【解决方案1】:
$ jq -r '.[].username' my_file.json
jdoe
jadoe

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多