Home > Enterprise >  how to properly pass arguments to jq
how to properly pass arguments to jq

Time:11-09

I'm trying to add a json file's name as a key to the file structure itself. For example:

Input:

test.json 
{}

Output:

test.json
{
    "test": {}
}

These are the commands I'm trying:

output=`cat $file` | jq --arg fn "$file_name" '.  = {"$fn" : {}}' 

or

# file_name already contains file name without extension
output=`cat $file | jq --argjson k '{"$file_name": {}}' '.  = $k'`

echo "$output" > $file

However, the outputs are:

test.json
{
     "$fn": {}
}

test.json
{
     "$file_name": {}
}

How do I make sure jq can recognize args as a variable and not a string literal ?

CodePudding user response:

Using input_filename (and rtrimstr to remove the extension):

jq '.[input_filename | rtrimstr(".json")] = {}' test.json

Using --arg and a variable initialized from outside:

jq --arg fn "test" '.[$fn] = {}' test.json 

Output:

{
  "test": {}
}

CodePudding user response:

Don't quote them. Things in double quotes are strings. Also make sure your command substitution surrounds the correct expression and avoid useless use of cat. Still (double) quote your shell variables (single quotes prevent expansion).

output="$(jq --arg fn "$file_name" '.  = {$fn: {}}' $file)"

or even:

output="$(jq --arg fn "$file_name" '.[$fn] = {}')"

The above assumes that your input file contains more than an empty object. Because if not, then you could simply do jq -n --arg fn "$file_name" '{$fn:{}}' without any input or printf '%s' "$file_name" | jq '{(.): {}}'

  • Related