1

I have a file with the below contents and a shell variable with some keys. I want to create nested JSON using all keys. eg:

file.json:
{
    "name":"..",
    "value":".."
}

shell variable which contains list of keys:

values=('one' 'two' 'three')

I want to create a variable like below:

{
   "all":{
        "one":  {
            "name":"..",
            "value":".."
        },
        "two":  {
            "name":"..",
            "value":".."
        },
        "three":  {
            "name":"..",
            "value":".."
        }
   }
}

I tried to pass the values are --arg to JQ, but it didnt work. JQ version: 1.5.

0

1 Answer 1

2

Newer versions of JQ populates an internal array ($ARGS.positional) with arguments given after --args on command-line, you can use it.

jq '{all: [{($ARGS.positional[]): .}] | add}' file --args "${values[@]}"

On older versions, you can use this approach:

printf '"%s"\n' "${values[@]}" |
    jq '{all: [{(inputs): .}] | add}' file -

But note that this is not as reliable as the above one, I highly recommend updating JQ.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.