Issue
I have a source file that looks like
{
"admin-user" : {
"index.md": "Index",
"user_profil.md": "User Profil"
}
}
By help of bash and jq I like to concat a string of the second level keys index.md
and user_profile.md
. Further I like replace .md
with .html
(key admin-user is unknown an can change)
This is where I hang:
KEYS=$(cat test.json | jq -r '.[]|keys')
concat_string=""
for i in $KEYS
do
md_name=${i/.md/.html}
concat_string="$concat_string$md_name"
done
echo $concat_string
Result:
["index.html","user_profil.html"]
So the result is an array. How can I concat a string with blanks between strings?
Solution
All of it can be done from within jq:
map(keys_unsorted[] | sub("\\.md$"; ".html"))
Alternatively, you can use to_entries
to access each .key
:
map(to_entries[].key | sub("\\.md$"; ".html"))
Both will give you an array of strings
["index.html","user_profil.html"]
which you can then -still in jq- concatenate using join
and a glue character:
jq -r 'map(keys_unsorted[] | sub("\\.md$"; ".html")) | join(" ")' test.json
or using the alternative approach:
jq -r 'map(to_entries[].key | sub("\\.md$"; ".html")) | join(" ")' test.json
Note: Using keys
instead of keys_unsorted
(as you did in your attempt) will additionally sort the keys.
Answered By - pmf Answer Checked By - Clifford M. (WPSolving Volunteer)