Home > Software design >  append json output before saving into file
append json output before saving into file

Time:09-29

I am trying to curl some URL which returns a json file, as follows

[
  10,
  20,
  30,
  40,
]

now I am trying to save these value in file with a variable assigned to it.

need output in file as

a=10
b=20
c=30
d=40

thanks in advance.

CodePudding user response:

You could use implode to create the letters by array index, which is provided in .key when to_entries is applied to an array.

jq -r 'to_entries[] | "\([.key   97] | implode)=\(.value)"'
a=10
b=20
c=30
d=40

Demo


To provide individual names, you can introduce an array of names and use transpose to make the alignment:

jq -r '
  [["Price", "Amount", "Value", "Tax"], .]
  | transpose[] | "\(first)=\(last)"
'
Price=10
Amount=20
Value=30
Tax=40

Demo

Note: The list could also be provided from outside jq:

  • using a JSON array
jq -r --argjson names '["Price", "Amount", "Value", "Tax"]' \
  '[$names, .] | transpose[] | "\(first)=\(last)"'
  • using positional parameters
jq -r '[$ARGS.positional, .] | transpose[] | "\(first)=\(last)"' \
  --args Price Amount Value Tax
  • Related