How do I update JSON file using PowerShell

Neo picture Neo · Mar 8, 2016 · Viewed 42.6k times · Source

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?

Answer

JPBlanc picture JPBlanc · Mar 8, 2016

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.