Sam
Sam

Reputation: 95

How do I update JSON file using PowerShell (Patch Method)

I have a json file like below, and I want to update values using a PowerShell script

{
  "rows": [{
    "id": 111,
    "name": "xrx",
    "serial": "A123456",
    "model": {
      "id": 8,
      "name": "wlw"
    },
    "model_number": "2323",
    "status_label": {
      "id": 22,
      "name": "out"
    }  
    }]
}

I want to edit the status label id and name (status_label -> id & name). Is there any way I can edit it with Powershell?

Upvotes: 0

Views: 1826

Answers (1)

theadzik
theadzik

Reputation: 138

You can use ConvertFrom-Json and ConvertTo-Json functions.

$Json = Get-Content C:\Temp\json.json | ConvertFrom-Json
$Json.rows.status_label.id = "newID"
$Json.rows.status_label.name = "newName"
$Json | ConvertTo-Json | Out-File C:\Temp\newJson.json

When you use ConvertFrom-Json you will get a PowerShell object which you can manipulate as every other object. Then you can convert the object back into Json string and overwrite the old file or save it as a new one.

Upvotes: 2

Related Questions