Nael
Nael

Reputation: 23

Append new element to JSON object in specific format using bash and jq

I would like to append an element to an existing JSON file where I have the working directory as the key and the working directory + the contents as the value in a string array format.

Lets say I have the following structure:

 Docs (Directory)
 |
 +-- RandomFile.json
 |    
 +-- Readme (Working Directory)
 |  |  
 |  +-- Readme.md
 |  +-- Readyou.md

What I would like to achieve is the structure below with the working directory as the prefix for every element in the array.

"Readme": ["Readme/Readme.md", "Readme/Readyou.md"]

From the output above, I would like to append that to the contents of the RandomFile.json which currently looks like this:

{
  "docs": {
    "Doc": ["doc1"]
  }
}

to this:

{
  "docs": {
    "Doc": ["doc1"],
    "Readme": ["Readme/Readme.md", "Readme/Readyou.md"]
  }
}

Is it something that can be managed straightforward using bash and jq?

Upvotes: 0

Views: 276

Answers (1)

chepner
chepner

Reputation: 530843

This requires jq 1.6 in order to use the --args option.

$ jq --arg wd "$(basename "$PWD")" '.docs+={($wd): $ARGS.positional | map("\($wd)/\(.)")}' ../RandomFile.json --args *
{
  "docs": {
    "Doc": [
      "doc1"
    ],
    "Readme": [
      "Readme/Readme.md",
      "Readme/Readyou.md"
    ]
  }
}
  1. The shell is used to pass the base name of the current working directory as the variable $wd.
  2. The shell is also used to pass the names of all the files in the current working directory as separate arguments.
  3. The file to edit is assumed to be ../RandomFile.json; if you only know that there is a JSON file in the parent, you can use ../*.json instead.
  4. Use += to update the .docs object of the original with a new key (the working directory) and list of file names. map prefixes each element of $ARGS.positional with $wd.

Upvotes: 1

Related Questions