Home > Blockchain >  Need help to create objects inside array
Need help to create objects inside array

Time:02-26

jq query as like this ,

jq -n  --arg cname "$1" --arg dns "$2" '
  {
    "extra_vars": {
      "oper_tasks": [ "records" ],
      "zone_info": [
        {
          "zone": "exmple.com",
          "records": [
            {
              "name": $cname,
              "type": "CNAME",
              "value": $dns,
              "ttl": 3600
            }
          ]
        }
      ]
    }
  }
'

The above jq cn produce something like this , cname and dns can be filled with arguments when we execute as script.

"extra_vars": {
    "oper_tasks": [
      "records"
    ],
    "zone_info": [
      {
        "zone": "exmple.com",
        "records": [
          {
            "name": "",
            "type": "CNAME",
            "value": "",
            "ttl": 3600
          }
        ]
      }
    ]
  }
}

how we can create more than one objects like below from an input file. something like how we do in for loop.

"extra_vars": {
"oper_tasks": [
  "records"
],
"zone_info": [
  {
    "zone": "exmple.com",
    "records": [
      {
        "name": <cname1 from input file>,
        "type": "CNAME",
        "value": "",
        "ttl": 3600
      },
      {
        "name": <cname2 from input file>,
        "type": "CNAME",
        "value": "",
        "ttl": 3600
      }
    ]
  }
]

}

CodePudding user response:

Imagine that you have a file cnames.txt where each line contains one CNAME domain followed by its value:

foo.example.com google.com
bar.example.com stackoverflow.com

Let us create that file:

cat <<EOF > cnames.txt
foo.example.com google.com
bar.example.com stackoverflow.com
EOF

You can "nest" one jq into the other by using --slurpfile described in the jq Manual. The following command should do what you want:

cat cnames.txt | xargs -n2 jq -n '{
    "name": $ARGS.positional[0],
    "type": "CNAME",
    "value": $ARGS.positional[1],
    "ttl": 3600
}' --args | jq -n --slurpfile records /dev/stdin '
  {
    "extra_vars": {
      "oper_tasks": [ "records" ],
      "zone_info": [
        {
          "zone": "example.com",
          "records": $records
        }
      ]
    }
  }
'

which returns:

{
  "extra_vars": {
    "oper_tasks": [
      "records"
    ],
    "zone_info": [
      {
        "zone": "example.com",
        "records": [
          {
            "name": "foo.example.com",
            "type": "CNAME",
            "value": "google.com",
            "ttl": 3600
          },
          {
            "name": "bar.example.com",
            "type": "CNAME",
            "value": "stackoverflow.com",
            "ttl": 3600
          }
        ]
      }
    ]
  }
}
  • Related