Reputation: 591
I want to insert new root element on my json with jq, my goal is to manipulate json hierarchy by adding one level before root one:
json example:
{
"option1":true
}
i want to obtain:
{
"root":
{
"option1":true
}
}
but when i do:
$ echo '{"option1":true}' | jq -r '. + {"root"}'
it inserts the element at the first level, and not before it:
{
"root":null
"option1":true
}
Is it even possible ?
Upvotes: 2
Views: 2901
Reputation: 1260
How about plain echo
and cat
?
echo "{\"root\":$(cat file.json)}" | jq
Upvotes: 0
Reputation: 1293
let me offer you an alternative approach, using a walk-path based unix utility jtc
:
bash $ jtc -u'[^0]' -T'{ "root": {} }' -f file.json
bash $
bash $ jtc file.json
{
"root": {
"option1": true
}
}
bash $
The changes applied right into the file (-f
ensures that)
UPDATE: with the latest jtc
version, template functionality has been extended, so for the same example to work, a slight change of template is required ({}
needs to be spelled as {{}}
):
bash $ jtc -u'[^0]' -T'{"root": {{}} }' file.json
{
"root": {
"option1": true
}
}
bash $
PS> Disclosure: I'm the creator of the jtc
tool
Upvotes: 2
Reputation: 295659
Put .
in the spot where you want your input data to be. In that case, that's as the value for which the root
string is a key.
jq '{"root": .}' <<<'{"option1": true}'
...properly emits:
{
"root": {
"option1": true
}
}
Upvotes: 6