Skip to content

Instantly share code, notes, and snippets.

@Johnz86
Created November 7, 2022 16:54
Show Gist options
  • Save Johnz86/a4d5015c4a16ca9bfe824299521cd73d to your computer and use it in GitHub Desktop.
Save Johnz86/a4d5015c4a16ca9bfe824299521cd73d to your computer and use it in GitHub Desktop.
Example how to add formated key and value to json file with powershell.
param([Parameter(Mandatory)]$key, [Parameter(Mandatory)]$value, $file='.\i18n.json')
if ($value -eq $null) {
$value = read-host -Prompt "Please enter a value"
}
function Format-Json([Parameter(Mandatory, ValueFromPipeline)][String] $json) {
$indent = 0;
($json -Split "`n" | % {
if ($_ -match '[\}\]]\s*,?\s*$') {
# This line ends with ] or }, decrement the indentation level
$indent--
}
$line = (' ' * $indent) + $($_.TrimStart() -replace '": (["{[])', '": $1' -replace ': ', ': ')
if ($_ -match '[\{\[]\s*$') {
# This line ends with [ or {, increment the indentation level
$indent++
}
$line
}) -Join "`n"
}
$json = Get-Content $file | Out-String | ConvertFrom-Json
$json | Add-Member -Type NoteProperty -Name $key -Value $value -Force
$json | Select-Object ($json | Get-Member -MemberType NoteProperty).Name | ConvertTo-Json | Format-Json | Set-Content $file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment