lepapareil
lepapareil

Reputation: 591

How can I insert a parent element to my json with jq?

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

Answers (3)

Quirino Gervacio
Quirino Gervacio

Reputation: 1260

How about plain echo and cat?

echo "{\"root\":$(cat file.json)}" | jq

Upvotes: 0

Dmitry
Dmitry

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

Charles Duffy
Charles Duffy

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

Related Questions