I have an existing JSON file with the following:
{
"buildDate": "2017-08-16",
"version": "v1.2.0"
}
How do you add new key-value pairs to an existing JSON file? For example, I would like to take the above JSON, and end up with this:
{
"buildDate": "2017-08-16",
"version": "v1.2.0",
"newKey1": "newValue1",
"newKey2": "newValue2"
}
I currently write to JSON with the following code:
@{buildDate="2017-08-16"; version="v1.2.0"} | ConvertTo-Json | Out-File .\data.json
To take advantage of JSON using PowerShell, we must be acquainted with two very important cmdlets: ConvertTo-JSON and ConvertFrom-JSON. (For those using PowerShell 7, be aware there have been changes and additions to the JSON cmdlets .)
PowerShell Add a key value pair to an existing hash table. Example. An example, to add a "Key2" key with a value of "Value2" to the hash table, using the addition operator: $hashTable = @{ Key1 = 'Value1' } $hashTable += @{Key2 = 'Value2'} $hashTable #Output Name Value ---- ----- Key1 Value1 Key2 Value2.
Json is NOT a hash - it is text. which would list the keys. Really? Here's what I see: Json is NOT a hash - it is text. which would list the keys. Its not a hash, the data type is string.
We need to understand three essential components in the JSON universe, which are the concept of object, array (which is a collection of objects), and value pairs. The first stop on our little JSON journey is going to be the value pair. It is comprised of a field name and a field value.
Convert the JSON data to a PowerShell object, add the new properties, then convert the object back to JSON:
$jsonfile = 'C:\path\to\your.json'
$json = Get-Content $jsonfile | Out-String | ConvertFrom-Json
$json | Add-Member -Type NoteProperty -Name 'newKey1' -Value 'newValue1'
$json | Add-Member -Type NoteProperty -Name 'newKey2' -Value 'newValue2'
$json | ConvertTo-Json | Set-Content $jsonfile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With