【问题标题】:How can I use jq to remove quotes from key names and remove braces?如何使用 jq 从键名中删除引号并删除大括号?
【发布时间】:2021-04-11 13:00:36
【问题描述】:

我有兴趣使用 jq 从 json 格式转换为 tfvars,即:

输入:

{
  "foo": "aaa",
  "bar": "bbb",
}

期望的输出:

foo = "aaa"
bar = "bbb"

我试过了

echo "{\"foo\": \"aaa\",\"bar\": \"bbb\"}" | jq '.[]'
"aaa"
"bbb"

【问题讨论】:

  • 非常接近,但引用有点偏离: echo "{\"foo\": \"aaa\",\"bar\": \"bbb\"}" | jq 'to_entries|map("(.key) = (.value|tostring)")|.[]' "foo = aaa" "bar = bbb"
  • 您需要使用 -r 标志调用 jq 以去除引号。仍然与预期的输出不匹配,但接近。

标签: json jq


【解决方案1】:

tfvars 规范很难得到,但数字不应该被引用,null 是一个特例,数组也可以作为值,例如https://learn.hashicorp.com/tutorials/terraform/google-cloud-platform-variables?in=terraform/gcp-get-started 举例如下:

cidrs = [ "10.0.0.0/16", "10.1.0.0/16" ]

所以以下应该更接近一般的解决方案:

jq -r '
  def q:
    if type | IN("string", "boolean") then "\"\(tostring)\"" 
    else .
    end;
  to_entries[] | "\(.key) = \(.value|q)"
'

【讨论】:

    【解决方案2】:

    修改之前的答案可能会奏效。

    jq -r 'to_entries[] | "\(.key) = \"\(.value)\""'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多