Jq 包含带有包含空格的变量的查询

Jq 包含带有包含空格的变量的查询

我在搜索一个 json 字段时遇到问题,该字段中包含空格,并且变量包含搜索词,该搜索词中也包含空格。我一直在使用contains搜索,但我不确定如何让它搜索整个短语。

COUNTRY="United States"
CITY='"New York"'

cat testdata | jq --arg COUNTRY "$COUNTRY" --arg CITY "$CITY" -r \
'.wireguard[] | select(.country == $COUNTRY) | select(.city|contains('$CITY'))'

尝试运行 jq 命令时,出现以下错误:

jq: error: syntax error, unexpected $end, expecting QQSTRING_TEXT or QQSTRING_INTERP_START or QQSTRING_END (Unix shell quoting issues?) at <top-level>, line 1:
.wireguard[] | select(.country == $COUNTRY) | select(.city|contains("New                                                                     
jq: 1 compile error

看来,尽管变量包含 qoutes,但变量中的空格正在停止查询。

我也尝试过select(.city|contains($CITY)),但没有返回任何结果(没有错误)。但是,select(.city|contains("New York"))查询运行得很好。即使CITY变量的内容是"New York".

如何在“包含”查询中使用其中包含空格的变量?

我正在测试的 Json:

{
  "wireguard": [
    {
      "gateway": "us-ga.wg",
      "country_code": "US",
      "country": "United States",
      "city": "Atlanta, GA",
      "isp": "Datapacket"
    },
    {
      "gateway": "us-ca.wg",
      "country_code": "US",
      "country": "United States",
      "city": "Los Angeles, CA",
      "isp": "Datapacket"
    },
    {
      "gateway": "us-ny.wg",
      "country_code": "US",
      "country": "United States",
      "city": "New York, NY",
      "isp": "M247"
    },
    {
      "gateway": "us-ut.wg",
      "country_code": "US",
      "country": "United States",
      "city": "Salt Lake City, UT",
      "isp": "100TB"
    },
    {
      "gateway": "us-fl.wg",
      "country_code": "US",
      "country": "United States",
      "city": "Miami, FL",
      "isp": "Quadranet"
    },
    {
      "gateway": "us-nj.wg",
      "country_code": "US",
      "country": "United States",
      "city": "New Jersey, NJ",
      "isp": "Quadranet"
    },
    {
      "gateway": "us-nv.wg",
      "country_code": "US",
      "country": "United States",
      "city": "Las Vegas, NV",
      "isp": "M247"
    }
  ]
}

答案1

您的 shell 定义意味着CITY它实际上在文本中包含双引号。这将无法匹配任何东西。

您使用$CITYis 作为 shell 变量而不是jq参数。此外,因为您在使用它时使用了引号,所以 shell 可以解析它 - 并且 JSON 在"New和之间的空格处分割York"

试试这个吧。我交换了 shell 变量的大小写,以便更清楚哪个是 shell 变量,哪个是用于jq

country='United States'
city='New York'

jq --arg COUNTRY "$country" --arg CITY "$city" -r \
'.wireguard[] | select(.country == $COUNTRY) | select(.city|contains($CITY))' testdata

输出

{
  "gateway": "us-ny.wg",
  "country_code": "US",
  "country": "United States",
  "city": "New York, NY",
  "isp": "M247"
}

相关内容