使用JQ实现多个提取值

nxowjjhe  于 2022-10-23  发布在  Linux
关注(0)|答案(1)|浏览(194)

我有这个JSON文件:

{
  "range": "Sheet!A2:B100",
  "majorDimension": "ROWS",
  "values": [
    [
      "customer1_name",
      "customer1@email.com",
      "customer1_phone",
      "customer1_city"
    ],
    [
      "customer2_name",
      "customer2@email.com",
      "customer2_phone",
      "customer2_city"
    ]
  ]
}

并且,从一个外壳脚本中,我想使用JQ来提取每个块的每个值,并将它们赋给一些变量。以下是预期结果:
对于此区块:

[
      "customer1_name",
      "customer1@email.com",
      "customer1_phone",
      "customer1_city"
    ],

结果应该是这样的:

VAR1 = "customer1_name"
VAR2 = "customer1@email.com"
VAR3 = "customer1_phone"
VAR4 = "customer1_city"

对于这个街区:

[
      "customer2_name",
      "customer2@email.com",
      "customer2_phone",
      "customer2_city"
    ],

结果应该是这样的:

VAR1 = "customer2_name"
VAR2 = "customer2@email.com"
VAR3 = "customer2_phone"
VAR4 = "customer2_city"

其思想是逐块读取JSON文件,以获取/检索vars中的所有值。

7cwmlq89

7cwmlq891#

像这样使用tr有点老套,但是:

$ cat input

{
  "range": "Sheet!A2:B100",
  "majorDimension": "ROWS",
  "values": [
    [
      "customer1_name",
      "customer1@email.com",
      "customer1_phone",
      "customer1_city"
    ],
    [
      "customer2_name",
      "customer2@email.com",
      "customer2_phone",
      "customer2_city"
    ]
  ]
}
$ jq -rc '.values[]' input | tr -d '["]' | while IFS=, read var1 var2 var3 var4; do echo "$var1 $var2 $var3 $var4"; done
customer1_name customer1@email.com customer1_phone customer1_city
customer2_name customer2@email.com customer2_phone customer2_city

您还可以执行以下操作:

$ jq -rc '.values[][]' input | while read name; read email; read phone; read city; do echo "$name $email $phone $city"; done;
customer1_name customer1@email.com customer1_phone customer1_city
customer2_name customer2@email.com customer2_phone customer2_city

相关问题