Created
November 7, 2022 16:54
-
-
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.
This file contains 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
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