Skip to content

Latest commit

 

History

History
91 lines (81 loc) · 1.7 KB

How to jq to copy array inside the dictionary.md

File metadata and controls

91 lines (81 loc) · 1.7 KB

(jump to the answer)

I have the following json

   [ 
       { 
          "name":"bucket1"
       },
       { 
          "name":"bucket1"
       }
    ]

I want to convert it to

{ 
   "buckets":[ 
      { 
         "name":"bucket1"
      },
      { 
         "name":"bucket1"
      }
   ]
}

How do I do this with jq?

A:

couple ways to do it with jtc:

# 1. update your JSON into a template read from <stdin>:
bash $ <<<'{"buckets":[]}' jtc -w[0] -u file.json
{
   "buckets": [
      {
         "name": "bucket1"
      },
      {
         "name": "bucket1"
      }
   ]
}
bash $ 

# or, if you like to merge it with the pre-existing values in the array:
bash $ <<<'{"buckets":["some pre-existing value"]}' jtc -w[0] -mi file.json
{
   "buckets": [
      "some pre-existing value",
      {
         "name": "bucket1"
      },
      {
         "name": "bucket1"
      }
   ]
}
bash $ 


#2. wrap it using a template:
bash $ jtc -T'{"buckets":{{}}}' file.json
{
   "buckets": [
      {
         "name": "bucket1"
      },
      {
         "name": "bucket1"
      }
   ]
}
bash $ 

# and if you like to make the changes right into ths file:
bash $ jtc -T'{"buckets":{{}}}' -f file.json 
bash $ jtc file.json
{
   "buckets": [
      {
         "name": "bucket1"
      },
      {
         "name": "bucket1"
      }
   ]
}
bash $