【问题标题】:How to escape $ in the value of the field如何在字段值中转义 $
【发布时间】:2020-05-04 19:12:45
【问题描述】:

需要获取对应name='robot$deployer'id的值。 $ 如何被转义,所以jq 只选择正确的 ID (1321) 而不是同时选择 (1321 和 1326)?当前脚本在下面打印两个 ID

[
  {
    "id": 1321,
    "name": "robot$deployer",
    "token": "",
    "description": "deployer",
    "project_id": 55,
    "expires_at": 1590799816,
    "disabled": false,
    "creation_time": "2020-04-29T10:50:16.029882-07:00",
    "update_time": "2020-04-29T10:50:16.029882-07:00"
  },
  {
    "id": 1326,
    "name": "robot$test",
    "token": "",
    "description": "test",
    "project_id": 55,
    "expires_at": 1590862956,
    "disabled": false,
    "creation_time": "2020-04-30T04:22:36.940445-07:00",
    "update_time": "2020-04-30T04:22:36.940445-07:00"
  }
]

测试脚本

#!/bin/bash

export PROJECT_INFO='[ { "id": 1321, "name": "robot$deployer", "token": "", "description": "deployer", "project_id": 55, "expires_at": 1590799816, "disabled": false, "creation_time": "2020-04-29T10:50:16.029882-07:00", "update_time": "2020-04-29T10:50:16.029882-07:00" }, { "id": 1326, "name": "robot$test", "token": "", "description": "test", "project_id": 55, "expires_at": 1590862956, "disabled": false, "creation_time": "2020-04-30T04:22:36.940445-07:00", "update_time": "2020-04-30T04:22:36.940445-07:00" } ]'

ROBOT_LOGIN="robot\$deployer"
export ROBOT_ID=$(echo $PROJECT_INFO | jq --arg robot_name "$ROBOT_LOGIN" 'if .[].name == "robot$deployer" then .[].id else empty end')
echo "ROBOT_ID:" $ROBOT_ID

更新了脚本的工作版本,谢谢@hobbs

export PROJECT_INFO='[ { "id": 1321, "name": "robot$deployer", "token": "", "description": "deployer", "project_id": 55, "expires_at": 1590799816, "disabled": false, "creation_time": "2020-04-29T10:50:16.029882-07:00", "update_time": "2020-04-29T10:50:16.029882-07:00" }, { "id": 1326, "name": "robot$test", "token": "", "description": "test", "project_id": 55, "expires_at": 1590862956, "disabled": false, "creation_time": "2020-04-30T04:22:36.940445-07:00", "update_time": "2020-04-30T04:22:36.940445-07:00" } ]'

ROBOT_LOGIN="robot\$deployer"
export ROBOT_ID=$(echo $PROJECT_INFO | jq --arg rl "${ROBOT_LOGIN}" '.[] | select(.name == $rl) | .id')
echo "ROBOT_ID:" $ROBOT_ID

【问题讨论】:

  • 转义没有问题。 $ 不需要任何转义。只是您的if ... then .[].id else empty end 不正确。 .[].id 计算为 所有 个 ID。

标签: json conditional-statements jq


【解决方案1】:

您尝试做的事情由 jq select 函数处理:

ROBOT_ID=$(jq '.[] | select(.name == "robot$deployer") | .id')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多