0

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?

1
  • There's a comma missing after "model_number": "2323" Commented Jul 15, 2019 at 18:26

1 Answer 1

2

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.

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

3 Comments

the form in json was changed, and because of that i can't change another time. any solutions? the status_label look like this after running this code: "status_label": "@{id=999; name=nn}"
How did the JSON change? If you check what $Json.rows.status_label is (with | Get-Member for example) you'll see that it's an object with 2 properties. Id and name. You have to dig deeper :)
@sam ConvertTo-Json has a -Depth flag, if the change was that the json got shallower it might help to set it higher

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.