skip to Main Content

Here is my input:

{
  "alias-name": "soufriere",
  "member-entry": {
    "alias-entry-name": [
      "21:00:f4:e9:d4:50:56:7e",
      "21:00:f4:e9:d4:50:56:7f"
    ]
  }
}
{
  "alias-name": "stromboli",
  "member-entry": {
    "alias-entry-name": [
      "21:00:f4:e9:d4:50:56:8e"
      "21:00:f4:e9:d4:50:56:9e"
    ]
  }
}

I’d like to turn this into output

alicreate "soufriere","21:00:f4:e9:d4:50:56:7e;21:00:f4:e9:d4:50:56:7f"
alicreate "stromboli","21:00:f4:e9:d4:50:56:8e;21:00:f4:e9:d4:50:56:9e"

I tried this:

jq -r --arg quote """ ("alicreate " + $quote + ."alias-name" + $quote + "," + $quote + ."member-entry"."alias-entry-name"[] + $quote)'

but it gives a one by one line instead of a sequential.

alicreate "soufriere","21:00:f4:e9:d4:50:56:7e"
alicreate "soufriere","21:00:f4:e9:d4:50:56:7f"
alicreate "stromboli","21:00:f4:e9:d4:50:56:8e"
alicreate "stromboli","21:00:f4:e9:d4:50:56:9e"

2

Answers


  1. Iterating over an array produces its items. To instead join the items into a single string, use the join filter. Also, inside strings you can use " to generate quotes, and string interpolation (…) to inject values.

    jq -r '"alicreate "(."alias-name")","(
      ."member-entry"."alias-entry-name" | join(";")
    )""'
    
    alicreate "soufriere","21:00:f4:e9:d4:50:56:7e;21:00:f4:e9:d4:50:56:7f"
    alicreate "stromboli","21:00:f4:e9:d4:50:56:8e;21:00:f4:e9:d4:50:56:9e"
    

    Demo

    Note that you might want to properly escape the values, rather than just enclosing them with double quotes, but which encoding to use highly depends on the use-case of your output.

    Login or Signup to reply.
  2. We can use the @csv filter to handle quoting for us:

    jq -r '
      [."alias-name", (."member-entry"."alias-entry-name" | join(";"))]
      | @csv
      | "alicreate " + .
    '
    
    alicreate "soufriere","21:00:f4:e9:d4:50:56:7e;21:00:f4:e9:d4:50:56:7f"
    alicreate "stromboli","21:00:f4:e9:d4:50:56:8e;21:00:f4:e9:d4:50:56:9e"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search