70

I have one json file mytest.json like below I want to update values using PowerShell script

update.json

{
    "update": [
        {
            "Name": "test1",        
            "Version": "2.1"
        },
        {
            "Name": "test2",        
            "Version": "2.1"
        }   
    ]
}

I want to write a PowerShell script where if Name=="test1" I want to update Version= "3" How can i do it using parameters?

2 Answers 2

136

Here is a way :

$a = Get-Content 'D:\temp\mytest.json' -raw | ConvertFrom-Json
$a.update | % {if($_.name -eq 'test1'){$_.version=3.0}}
$a | ConvertTo-Json -depth 32| set-content 'D:\temp\mytestBis.json'

According to @FLGMwt and @mikemaccana I improve the ConvertTo-Json with -depth 32 because the default depth value is 2 and for object deeper than 2 you will receive class informations in spite of objects.

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

3 Comments

Be ware that ConvertTo-Json has a default depth of 2. Deep json will get ToString'd which is probably not what you want. If you have more nested json, use the Depth parameter: ConvertTo-Json -Depth 20
@mikemaccana Thanks for the adjusting with depth, but 1000 is a bit to important. I also add a small explanation.
17

I have also faced the same kind of issue. I was looking to change the records of the below JSON file

{
"SQS_QUEUE_URL":  "https://que-url.com/server1",
"SQS_EVENTS_QUEUE_URL":  "https://events-server.com/server1/development_events",
"REGION":  "region1",
"BUCKET":  "test-bucket",
"AE_WORK_PATH":  "C:\\workpath\\path1",
"ENV":  "env"

}

Finally, I managed to find the easiest way to generate a JSON file from Powershell.

$json = Get-Content "c:\users\bharat.gadade\desktop\test.json" | ConvertFrom-Json 
$json.SQS_QUEUE_URL = "https://que-url.com/server2"
$json.SQS_EVENTS_QUEUE_URL = "https://events-server.com/Server2/development_events"
$json.REGION = "region1 "
$json.BUCKET = "test-bucket"
$json.AE_WORK_PATH = "C:\workpath\path1"
$json.ENV = "env"
$json | ConvertTo-Json | Out-File "c:\users\bharat.gadade\desktop\test.json"

1 Comment

To add to this, for layered json data, you can reference the tags beneath the header with the period operator. so if your Json is like: {"Settings": {"AWS_REGION": "us-east-1" }} you can use: $json.Settings.AWS_REGION to set or read the entry!

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.