My goal is to output a JSON object using jq
on the output of a find
command in bash. It could either be a one-line command or a bash script.
I have this command which creates JSON objects from each line of output:
find ~/ -maxdepth 1 -name "D*" | \
while read line; \
do jq -n \
--arg name "$(basename "$line")" \
--arg path "$line" \
'{name: $name, path: $path}'; \
done
The output looks like this:
{
"name": "Desktop",
"path": "/Users/username/Desktop"
}
{
"name": "Documents",
"path": "/Users/username/Documents"
}
{
"name": "Downloads",
"path": "/Users/username/Downloads"
}
But I need these objects to be in an array, and I need the array to be the value of a a parent object's single key called items
, like so:
{"items": [
{
"name": "Desktop",
"path": "/Users/username/Desktop"
},
{
"name": "Documents",
"path": "/Users/username/Documents"
},
{
"name": "Downloads",
"path": "/Users/username/Downloads"
}
]
}
I tried adding the square brackets to the jq
output string for each line ('[{name: $name, path: $path}]';
) and that adds the brackets but not the commas between the array elements.
I found possible solutions here but I could not figure out how to use them while looping through each line.