【问题标题】:multi extract values with JQ使用 JQ 多提取值
【发布时间】:2021-09-01 14:51:20
【问题描述】:

我有这个 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"
    ]
  ]
}

而且,我想从一个 shell 脚本中使用 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 中的所有值。

有什么意见或建议吗?

谢谢

【问题讨论】:

  • 我发现了这个:jq -r '.values | .[1]' 但是现在如何逐个提取值?

标签: json linux shell jq script


【解决方案1】:

像这样使用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

【讨论】:

  • 这里没有引号不是吗? jq '-rc .values[][] 输入'
  • 对不起jq '-rc .values[][]' input_file
  • 如果你要使用引号,你应该引用所有内容:'jq' '-rc' '.values[][]' 'input'。没有一半的措施。
  • 但你肯定想要jq '-rc .values[][]',因为-rc.values[][]必须是不同的参数。
  • 如果设置了 nullglob,您确实需要引用 .values[][]
猜你喜欢
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多