Issue
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 ?
Solution
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": {}
}
Answered By - pmf Answer Checked By - Katrina (WPSolving Volunteer)