0

I'm interested in transforming from json format to tfvars using jq, i.e.:

Input:

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

Desired output:

foo = "aaa"
bar = "bbb"

I tried

echo "{\"foo\": \"aaa\",\"bar\": \"bbb\"}" | jq '.[]'
"aaa"
"bbb"
  • 3
    Does this answer your question? [How to convert a JSON object to key=value format in jq?](https://stackoverflow.com/questions/25378013/how-to-convert-a-json-object-to-key-value-format-in-jq) – oguz ismail Jan 05 '21 at 18:46
  • It's pretty close, but the quoting is a little bit off: echo "{\"foo\": \"aaa\",\"bar\": \"bbb\"}" | jq 'to_entries|map("\(.key) = \(.value|tostring)")|.[]' "foo = aaa" "bar = bbb" – Serge Bryant Jan 05 '21 at 18:57
  • You need to invoke jq with the `-r` flag to get rid of quotes. Still doesn't match the expected output, but close. – oguz ismail Jan 05 '21 at 18:59

2 Answers2

1

The tfvars specification is hard to come by, but numbers should not be quoted, null is a special case, and arrays are also allowed as values, e.g. https://learn.hashicorp.com/tutorials/terraform/google-cloud-platform-variables?in=terraform/gcp-get-started gives the following as an example:

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

So the following should be closer to a general solution:

jq -r '
  def q:
    if type | IN("string", "boolean") then "\"\(tostring)\"" 
    else .
    end;
  to_entries[] | "\(.key) = \(.value|q)"
'
peak
  • 105,803
  • 17
  • 152
  • 177
0

A modification of the earlier answer might work.

jq -r 'to_entries[] | "\(.key) = \"\(.value)\""'
user197693
  • 1,935
  • 10
  • 8