简体   繁体   中英

How to modify Json using Powershell

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.

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 , .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM