0

I have like this variables in my bash script:

server1_name = 'server-1'
server1_url = 'http://server-1.net'

server2_name = 'server-2'
server2_url = 'http://server-2.net'

How I can create like this json using my variables and set to new var:

[
  {
    "name": "server-1",
    "url": "http://server-1.net"
  },
  {
    "name": "server-2",
    "url": "http://server-2.net"
  }
]

What I tried:

export jsonArray = $("[{\"name\":"$server1_name",\"url\":\"$server1_url\"},{\"name\":"$server2_name",\"url\":\"$server2_url\"}]" | jq -rec .)
3
  • Do you want a dynamic solution, or are those examples the real values? Commented Aug 26, 2021 at 14:34
  • Those examples the real values @0stone0 Commented Aug 26, 2021 at 14:35
  • You can show both options Commented Aug 26, 2021 at 14:36

2 Answers 2

4

Pass your strings using --arg, then you can create the JSON as expected:

#!/bin/bash

server1_name='server-1'
server1_url='http://server-1.net'

server2_name='server-2'
server2_url='http://server-2.net'

result=$(jq -n \
    --arg name1 "$server1_name" \
    --arg url1 "$server1_url" \
    --arg name2 "$server2_name" \
    --arg url2 "$server2_url" \
    '[ { "name": $name1, "url": $url1 }, { "name": $name2, "url": $url2 } ]')

echo "$result"

Will produce:

[
  {
    "name": "server-1",
    "url": "http://server-1.net"
  },
  {
    "name": "server-2",
    "url": "http://server-2.net"
  }
]
Sign up to request clarification or add additional context in comments.

2 Comments

How I can set result to new var to export it?
Please see my edit, forgot you want it in a other variable!
1

You can construct two arrays of names and urls, then adapt this answer to "zip" the two arrays together into the desired array of objects.

jq -n \
    --arg name1 "$server1_name" \
    --arg url1 "$server1_url" \
    --arg name2 "$server2_name" \
    --arg url2 "$server2_url" \
'[$name1, $name2] as $names |
 [$url1, $url2] as $urls |
  [([$names, $urls] | transpose[]) as [$name, $url] |{$name, $url}]'

The benefit is that as the number of name/url pairs grows, you only need to modify the first two filters that define $names and $urls; the rest of the filter stays the same. You could even separate this into separate uses of jq, to facilitate the definition of a large list of servers.

names=$(jq -n --arg v1 "$server1_name" --arg v2 "$server2_name" '[$v1, $v2]')

urls=$(jq -n --arg v1 "$server1_url" --arg v2 "$server2_url" '[$v1, $v2]')

jq -n \
   --argjson names "$names" \
   --argjson urls "$urls" \
   '[([$names, $urls] | transpose[]) as [$name, $url] | {$name, $url}]'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.