64

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?

wonea
  • 4,783
  • 17
  • 86
  • 139
Neo
  • 15,491
  • 59
  • 215
  • 405

2 Answers2

127

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.

JPBlanc
  • 70,406
  • 17
  • 130
  • 175
  • 55
    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` – FLGMwt Jan 26 '17 at 23:57
  • Reference for the `depth` issue: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json?view=powershell-6 – mikemaccana Apr 19 '19 at 21:39
  • @mikemaccana Thanks for the adjusting with `depth`, but 1000 is a bit to important. I also add a small explanation. – JPBlanc Apr 20 '19 at 07:13
14

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"
Bharat Gadade
  • 437
  • 4
  • 6
  • 4
    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! – Kevinsyel Mar 16 '21 at 00:58