【问题标题】:creating a nested json string with jq用 jq 创建一个嵌套的 json 字符串
【发布时间】:2019-07-30 13:44:41
【问题描述】:

如何使用 jq 创建以下 json?

{"RedrivePolicy":{"deadLetterTargetArn":"arn:aws:sqs:us-east-1:12345678:reptar-dlq","maxReceiveCount":"15"}}

【问题讨论】:

  • 每个 JSON 值也是一个有效的 jq 程序。所以提出的问题有一个微不足道的答案。这就是你要问的问题吗?
  • 是的,确实如此。我没有意识到这很简单。我已经发布了对我有用的答案。

标签: json shell unix jq


【解决方案1】:

如果 jq 不是严格要求,或者您可以使用 unix walk-path 实用程序 jtc

bash $ <<<'{"RedrivePolicy":{"deadLetterTargetArn":"arn:aws:sqs:us-east-1:12345678:reptar-dlq","maxReceiveCount":"15"}}' jtc 
{
   "RedrivePolicy": {
      "deadLetterTargetArn": "arn:aws:sqs:us-east-1:12345678:reptar-dlq",
      "maxReceiveCount": "15"
   }
}
bash $ 

如果你想把它写到文件中,那么做:

bash $ <<<'{"RedrivePolicy":{"deadLetterTargetArn":"arn:aws:sqs:us-east-1:12345678:reptar-dlq","maxReceiveCount":"15"}}' jtc - -f your.json
bash $ 
bash $ jtc your.json
{
   "RedrivePolicy": {
      "deadLetterTargetArn": "arn:aws:sqs:us-east-1:12345678:reptar-dlq",
      "maxReceiveCount": "15"
   }
}
bash $ 

实际上,你的输出是一个 JSON,jtc 这里只是验证它并保存到文件中。如果您不需要验证(并确保它是有效的 JSON),那么您可以将其直接转储到文件中:

bash $ <<<'{"RedrivePolicy":{"deadLetterTargetArn":"arn:aws:sqs:us-east-1:12345678:reptar-dlq","maxReceiveCount":"15"}}' cat >file.json

PS> 披露:我是jtc - 用于 JSON 操作的 shell cli 工具的创建者

【讨论】:

  • 谢谢@Dmitry。这看起来是一个非常有用的工具。我只在我的 jenkins env 中安装了 jq ,所以强制使用它。这绝对是工具箱中另一个有用的工具。
【解决方案2】:

我能够使用下面列出的命令创建 jq json -

redrive_policy=$(jq -n --arg arn "$dlq_arn" --arg max "$max_count" '{RedrivePolicy:{deadLetterTargetArn: $arn,maxReceiveCount: $max}}')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2022-10-21
    • 2023-01-20
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多