Created
August 14, 2026 15:20
-
-
Save peteraritchie/d6c5b1dcfaf00b0dead64339dfb10b23 to your computer and use it in GitHub Desktop.
A PowerShell script to add a JSON object to a specified path within a JSON file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .SYNOPSIS | |
| Adds a JSON object to a specified path within a JSON file. | |
| .DESCRIPTION | |
| This script reads a JSON file, adds a specified JSON object to a given path within that file, and outputs the modified JSON. | |
| .PARAMETER Path | |
| The path to the JSON file. | |
| .PARAMETER JSONText | |
| The JSON text to add. | |
| .PARAMETER JSONPath | |
| The path within the JSON file where the object should be added. | |
| If not supplied, the object will be added to the root of the JSON file. | |
| .EXAMPLE | |
| Add-JsonObject.ps1 .\global.json '{"test":{"runner": "Microsoft.Testing.Platform"}}' | |
| #> | |
| param( | |
| [Parameter(Mandatory = $true, Position = 0)] | |
| [string]$Path, | |
| [Parameter(Mandatory = $true, Position = 1)] | |
| [string]$JSONText, | |
| [string]$JSONPath = "" | |
| ) | |
| $rootObject = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json; | |
| $jsonObject = $JSONText | ConvertFrom-Json; | |
| $targetValue = $rootObject; | |
| $children = $JSONPath.Split('.'); | |
| $JSONPath.Split('.') | ForEach-Object { if([string]::IsNullOrEmpty($_) -eq $false) { $targetValue = $targetValue.$_ } } | |
| Write-Verbose "Adding property '$($jsonObject.PSObject.Properties.Name)' with value $($jsonObject.PSObject.Properties.Value)"; | |
| $result = $targetValue | Add-Member -Type NoteProperty -Name $jsonObject.PSObject.Properties.Name -Value $jsonObject.PSObject.Properties.Value -Force; | |
| $rootObject | ConvertTo-Json; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment