Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new key value pair to JSON file in powershell.

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
like image 710
Roka545 Avatar asked Aug 16 '17 22:08

Roka545


People also ask

How do I use JSON with PowerShell?

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 .)

How to add a key value pair to an existing hash table?

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.

Is a JSON file a hash?

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.

What is a value pair in JSON?

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.


1 Answers

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
like image 186
Ansgar Wiechers Avatar answered Nov 15 '22 07:11

Ansgar Wiechers