Home > Back-end >  Reshape json values to value content
Reshape json values to value content

Time:03-27

I'm not sure if this is even possible with jq but would be very happy if.

The data I receive must be transformed to build parameters for tools I use.

One tool requires the following string as parameter (it's not a json or json object - simple string):

-parameter="{<IP>,[<NAME>,<ALIAS>],<COMMENT>}"

The source data I recieve is json and looks like this

    {
      "MAINSERVER": {
        "COMMENT": "Server",
        "IP": "1.1.1.1",
        "NAME": "Server1",
        "VERSION": "19.4"
      },
      "DATASERVER": [
        {
          "ALIAS": "alias02",
          "IP": "1.1.1.2",
          "NAME": "server02"
        },
        {
          "ALIAS": "alias03",
          "IP": "1.1.1.3",
          "NAME": "server03"
        }
      ]
    }

I would like to transform each object array in DATASERVER to a string and push it to the key parameter.

{
  "parameter": [
    "{1.1.1.2,[server02,alias02],staticComment}",
    "{1.1.1.3,[server03,alias03],staticComment}"
  ]
}   

Any support would be really appreciated.

CodePudding user response:

Producing the sample output from the question

{parameter: .DATASERVER | map("{\(.IP),[\(.NAME),\(.ALIAS)],staticComment}")}
{
  "parameter": [
    "{1.1.1.2,[server02,alias02],staticComment}",
    "{1.1.1.3,[server03,alias03],staticComment}"
  ]
}

Demo


Producing the output from your own solution in a simpler way

{parameter: [.DATASERVER | map("{\(.NAME),[\(.IP),\(.ALIAS)]}")]}
{
  "parameter": [
    [
      "{server02,[1.1.1.2,alias02]}",
      "{server03,[1.1.1.3,alias03]}"
    ]
  ]
}

Demo

CodePudding user response:

Ok, I managed it on my own. I thought it's more complex.

Here is my query

.DATASERVER  | map((\"{\"   .NAME   \",[\"    .IP   \",\"    .ALIAS   \"]}\") ) | {parameter: [.] }

result

{
    "parameter": [
        [
            "{server02,[1.1.1.2,alias02]}",
            "{server03,[1.1.1.3,alias03]}"
        ]
    ]
}

CodePudding user response:

Starting with the given template, you could write:

jq --arg parameter "{<IP>,[<NAME>,<ALIAS>],<COMMENT>}" '
 [.DATASERVER[] as $l
  | $parameter 
  | sub("<IP>"; $l.IP)
  | sub("<NAME>"; $l.NAME) 
  | sub("<ALIAS>"; $l.ALIAS)
  | sub("<COMMENT>"; $l.COMMENT // "staticComment") ]
 | {parameter: .}
'
  • Related