【问题标题】:jq query to pull values from json file to create a listingjq 查询从 json 文件中提取值以创建列表
【发布时间】:2022-08-14 17:10:50
【问题描述】:

给定这个输入小样本:

{
  \"_format_version\": \"1.1\",
  \"_workspace\": \"test\",
  \"services\": [
    {
      \"connect_timeout\": 60000,
      \"host\": \"host-name-test.com\",
      \"name\": \"name-of-service\",
      \"path\": \"/test/oauthpass\",
      \"port\": 777,
      \"protocol\": \"http\",
      \"read_timeout\": 1000,
      \"retries\": 1,
      \"write_timeout\": 1000,
      \"routes\": [
        {
          \"hosts\": [
            \"Google.com\"
          ],
          \"name\": \"com.testing.active.oauth\",
          \"methods\": [
            \"POST\"
          ],
          \"paths\": [
            \"/vendors/otest/pass/?$\"
          ],
          \"path_handling\": \"v8\",
          \"preserve_host\": false,
          \"protocols\": [
            \"https\"
          ],
          \"regex_priority\": 0,
          \"strip_path\": true,
          \"https_redirect_status_code\": 426,
          \"request_buffering\": true,
          \"response_buffering\": true
        }
      ]
    }
}

试图从提取某些值的数据中获取列表,如下面的列表:

host-name-test.com, Google.com, POST, HTTPS

到目前为止我工作的命令是

cat /tmp/petecar.json | jq -r \' .services[] | .routes[] | ( .hosts[] + \"/\" + .paths[]) \' | more

但我无法访问服务下的值,请提供一些有关如何获取值的示例

  • 您的 jq 过滤器有效(请参阅demo),您的 JSON 无效。在倒数第二行中缺少一个数组右括号]
  • 我不得不更改要发布的数据并错过了那个括号,但是对于 jq 我需要添加到它以便获得类似这样的服务下的值 - jq -r \'.services[] | .host + \" \" | .routes[] | ( .hosts[] + \"/\" + .paths[])\' /tmp/petecar.json 但我在试图弄清楚如何编写 jq 时出错
  • 如果您包含错误消息会有所帮助,这样人们就可以看到出了什么问题,以及该失败命令的具体预期输出,因此人们可以尝试更正/重新创建您打算实现的目标。没有,人们不得不猜测。这是我的:你的意思是.services[] | .host + \" \", (.routes[] | ( .hosts[] + \"/\" + .paths[]))Demo
  • 抱歉,这是我收到的命令和错误消息
  • jq -r \'.services[] | .host + \" \" + .routes[].hosts\' /tmp/petecar.json jq: error (at /tmp/petecar.json:21824): string (\"host-name...) and array ([\"Google.c...) 无法添加

标签: jq


【解决方案1】:

routes 有一个数组值,因此不能与字符串连接。您可以使用 join 将该数组转换为单个字符串:

jq -r '.services[] | .host + " " + (.routes[].hosts | join(","))'

输出:

host-name-test.com Google.com

或者,使用 string interpolation) 会自动将任何值序列化为其字符串表示形式:

jq -r '.services[] | "\(.host) \(.routes[].hosts)"'

输出:

host-name-test.com ["Google.com"]

join 和字符串插值可以结合使用,为您提供与第一个命令相同的输出:

jq -r '.services[] | "\(.host) \(.routes[].hosts|join(","))"'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 2017-11-26
    • 2018-08-13
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    相关资源
    最近更新 更多