lem
lem

Reputation: 31

how to properly pass arguments to jq

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 ?

Upvotes: 0

Views: 2710

Answers (2)

knittl
knittl

Reputation: 265727

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 '{(.): {}}'

Upvotes: 1

pmf
pmf

Reputation: 36391

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": {}
}

Upvotes: 3

Related Questions