0

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?

1
  • If Readme is the working directory, do you know that ../RandomFile.json is the name of the file to modify, or just that there is a single JSON file in the parent directory that should be modified? Commented Jan 13, 2020 at 16:01

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.