1

I have the following JSON held in a file "test.json":

{
  "metadata": [
    {
      "src": [
        {
          "files": [
            "src/**.csproj"
          ]
        }
      ],
      "dest": "api",
      "disableGitFeatures": false,
      "disableDefaultFilter": false
    }
  ]
}

I'd like to modify the "src" element. Instead of:

  "src": [
    {
      "files": [
        "src/**.csproj"
      ]
    }
  ],

It needs to be:

    "src": [
        {
          "files": [
            "*.csproj"
          ],
          "cwd":".."
        }
      ],

Where I modify the first element of "files" and add "cwd". This should be straight forward but I'm struggling to achieve this in powershell. Can anyone point me in the right direction of any examples of this?

Thanks for any pointers in advance.

1 Answer 1

5

You can do the following:

$JSONObject = Get-Content test.json -Raw | ConvertFrom-Json
$JSONObject.metadata.src.files = ,'*.csproj'
$JSONObject.metadata.src | Add-Member -Name 'cwd' -Value '..' -MemberType NoteProperty
$JSONObject | ConvertTo-Json -Depth 5 | Set-Content test.json

The tricky part is to make sure the .files value is an array of a single element. You can do this with the array subexpression operator @() or the unary operator ,.

Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly!! I just added "-force" to the end of the Add-Member in case it was run multiple times but this worked perfectly for me, thanks loads!! :D

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.